给定两个整数X和Y ,代表两个正整数的按位异或和按位与,任务是计算这两个正整数的按位或值。
例子:
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 个自然数的所有可能对。对于每一对,检查该对的按位异或和按位与是否分别为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)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。