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

📅  最后修改于: 2021-10-26 05:10:52             🧑  作者: Mango

给定两个整数XY ,代表两个正整数的按位异或按位与,任务是计算这两个正整数的按位或值。

例子:

朴素的方法:解决这个问题的最简单的方法是迭代到XY的最大值,比如N ,并生成前N 个自然数的所有可能对。对于每一对,检查该对的按位异或和按位与是否分别为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)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程