给定两个整数X和Y ,分别表示两个正整数的按位XOR和按位与,任务是计算这两个正整数的按位或值。
例子:
Input: X = 5, Y = 2
Output: 7
Explanation:
If A and B are two positive integers such that A ^ B = 5, A & B = 2, then the possible value of A and B is 3 and 6 respectively.
Therefore, (A | B) = (3 | 6) = 7.
Input: X = 14, Y = 1
Output: 15
Explanation:
If A and B are two positive integers such that A ^ B = 14, A & B = 1, then the possible value of A and B is 7 and 9 respectively.
Therefore, (A | B) = (7 | 9) = 15.
天真的方法:解决此问题的最简单方法是迭代到X和Y的最大值(例如N) ,并生成前N个自然数的所有可能对。对于每对,检查该对的按位XOR和按位AND分别为X和Y。如果发现为真,则打印该对的按位或。
时间复杂度: O(N 2 ),其中N = max(X,Y)
辅助空间: O(1)
高效方法:为了优化上述方法,该思想基于以下观察结果:
(A ^ B) = (A | B) – (A & B)
=> (A | B) = (A ^ B) + (A & B) = X + Y
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to calculate Bitwise OR from given
// bitwise XOR and bitwise AND values
int findBitwiseORGivenXORAND(int X, int Y)
{
return X + Y;
}
// Driver Code
int main()
{
int X = 5, Y = 2;
cout << findBitwiseORGivenXORAND(X, Y);
}
Java
// Java program to implement
// the above approach
class GFG {
// Function to calculate Bitwise OR from given
// bitwise XOR and bitwise AND values
static int findBitwiseORGivenXORAND(int X, int Y)
{
return X + Y;
}
// Driver Code
public static void main (String[] args)
{
int X = 5, Y = 2;
System.out.print(findBitwiseORGivenXORAND(X, Y));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 program to implement
# the above approach
# Function to calculate Bitwise OR from
# given bitwise XOR and bitwise AND values
def findBitwiseORGivenXORAND(X, Y):
return X + Y
# Driver Code
if __name__ == "__main__" :
X = 5
Y = 2
print(findBitwiseORGivenXORAND(X, Y))
# This code is contributed by AnkitRai01
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to calculate Bitwise OR from given
// bitwise XOR and bitwise AND values
static int findBitwiseORGivenXORAND(int X, int Y)
{
return X + Y;
}
// Driver Code
public static void Main(string []args)
{
int X = 5, Y = 2;
Console.Write(findBitwiseORGivenXORAND(X, Y));
}
}
// This code is contributed by ipg2016107
Javascript
7
时间复杂度: O(1)
辅助空间: O(1)