📌  相关文章
📜  从给定的按位与和按位XOR值计算两个整数的按位或

📅  最后修改于: 2021-04-22 00:59:33             🧑  作者: Mango

给定两个整数XY ,分别表示两个正整数的按位XOR按位与,任务是计算这两个正整数的按位或值。

例子:

天真的方法:解决此问题的最简单方法是迭代到XY的最大值(例如N) ,并生成前N个自然数的所有可能对。对于每对,检查该对的按位XOR和按位AND分别为XY。如果发现为真,则打印该对的按位或

时间复杂度: O(N 2 ),其中N = max(X,Y)
辅助空间: O(1)

高效方法:为了优化上述方法,该思想基于以下观察结果:

下面是上述方法的实现:

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)