📌  相关文章
📜  查找具有给定按位或和按位异或值的所有可能对

📅  最后修改于: 2022-05-13 01:56:08.659000             🧑  作者: Mango

查找具有给定按位或和按位异或值的所有可能对

给定两个正整数AB表示两个正整数的按位异或和按位或,任务是找到所有可能的对(x, y)使得x ^ y等于Ax | y等于B

例子:

朴素方法:解决问题的最简单方法是生成所有可能的对,并为每一对检查它们的位异或和位或是否分别等于AB。

时间复杂度: O(B 2 )
辅助空间: O(1)

高效方法:这个想法是遍历x的所有可能值,并使用XOR 的属性,如果x ^ y = A ,则x ^ A = y找到y的所有可能值。请按照以下步骤解决问题:

  • 使用变量i1迭代到B并执行以下操作:
    • 将变量y初始化为i ^ A
    • 检查y的值是否大于0(i | y)是否等于B。
    • 如果发现为真,则打印iy的值。

下面是上述方法的实现:

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to find pairs with
// XOR equal to A and OR equal to B
void findPairs(int A, int B)
{
    // Iterate from 1 to B
    for (int i = 1; i <= B; i++) {
        int y = A ^ i;
 
        // Check if (i OR y) is B
        if (y > 0 and (i | y) == B) {
            cout << i << " " << y << endl;
        }
    }
}
 
// Driver Code
int main()
{
    int A = 8, B = 10;
 
    findPairs(A, B);
    return 0;
}


Java
// Java code for the above approach
import java.util.*;
 
class GFG{
 
// Function to find pairs with
// XOR equal to A and OR equal to B
static void findPairs(int A, int B)
{
     
    // Iterate from 1 to B
    for(int i = 1; i <= B; i++)
    {
        int y = A ^ i;
 
        // Check if (i OR y) is B
        if (y > 0 && (i | y) == B)
        {
            System.out.println(i + " " + y);
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int A = 8, B = 10;
 
    findPairs(A, B);
}
}
 
// This code is contributed by Hritik


Python3
# Python3 code for the above approach
 
# Function to find pairs with
# XOR equal to A and OR equal to B
def findPairs(A, B):
     
    # Iterate from 1 to B
    for i in range(1, B + 1):
         
        y = A ^ i
         
        # Check if (i OR y) is B
        if (y > 0 and (i | y) == B):
            print(i, " ", y)
 
# Driver Code
A = 8
B = 10
 
findPairs(A, B)
 
# This code is contributed by amreshkumar3


C#
// C# code for the above approach
using System;
class GFG
{
     
    // Function to find pairs with
    // XOR equal to A and OR equal to B
    static void findPairs(int A, int B)
    {
          
        // Iterate from 1 to B
        for(int i = 1; i <= B; i++)
        {
            int y = A ^ i;
      
            // Check if (i OR y) is B
            if (y > 0 && (i | y) == B)
            {
                Console.WriteLine(i + " " + y);
            }
        }
    }
 
  // Driver code
  static void Main ()
  {
    int A = 8, B = 10;
  
    findPairs(A, B);
  }
}
 
// This code is contributed by suresh07.


Javascript


输出:
2 10
10 2

时间复杂度: O(B)
辅助空间: O(1)