查找具有给定按位或和按位异或值的所有可能对
给定两个正整数A和B表示两个正整数的按位异或和按位或,任务是找到所有可能的对(x, y)使得x ^ y等于A和x | y等于B 。
例子:
Input: A = 5, B = 7
Output:
2 7
3 6
6 3
7 2
Explanation:
7( XOR )2 = 5 and 7( OR )2 = 7
3( XOR )6 = 5 and 3( OR )6 = 7
Input: A = 8, B = 10
Output:
2 10
10 2
朴素方法:解决问题的最简单方法是生成所有可能的对,并为每一对检查它们的位异或和位或是否分别等于A和B。
时间复杂度: O(B 2 )
辅助空间: O(1)
高效方法:这个想法是遍历x的所有可能值,并使用XOR 的属性,如果x ^ y = A ,则x ^ A = y找到y的所有可能值。请按照以下步骤解决问题:
- 使用变量i从1迭代到B并执行以下操作:
- 将变量y初始化为i ^ A 。
- 检查y的值是否大于0且(i | y)是否等于B。
- 如果发现为真,则打印i和y的值。
下面是上述方法的实现:
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)