📜  位与或位与之和等于N的非负对

📅  最后修改于: 2021-05-06 18:30:48             🧑  作者: Mango

给定一个整数N,任务是找到这样所有非负对(A,B),其按位或和按位的AND A的总和,B等于N,,(A | B)+(A& B)= N。

例子:

天真的方法:最简单的方法是在[0,N]范围内进行迭代并打印满足条件(A | B)+(A&B)= N的那些对(A,B)

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:为了优化上述方法,该思想基于以下观察结果:所有总和等于N的非负对都满足给定条件。因此,使用变量i[0,N]范围内进行迭代并打印对i(N – i)

下面是上述方法的实现。

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print all pairs whose
// sum of Bitwise OR and AND is N
void findPairs(int N)
{
    // Iterate from i = 0 to N
    for (int i = 0; i <= N; i++) {
 
        // Print pairs (i, N - i)
        cout << "(" << i << ", "
             << N - i << "), ";
    }
}
 
// Driver Code
int main()
{
    int N = 5;
    findPairs(N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to print all pairs whose
// sum of Bitwise OR and AND is N
static void findPairs(int N)
{
     
    // Iterate from i = 0 to N
    for(int i = 0; i <= N; i++)
    {
         
        // Print pairs (i, N - i)  
        System.out.print( "(" + i + ", " +
                          (N - i) + "), ");
   }
}
 
// Driver code
public static void main(String[] args)
{
    int N = 5;
     
    findPairs(N);
}
}
 
// This code is contributed by ajaykr00kj


Python3
# Python3 program for the above approach
 
# Function to print all pairs whose
# sum of Bitwise OR and AND is N
def findPairs(N):
     
     # Iterate from i = 0 to N
     for i in range(0, N + 1):
         
        # Print pairs (i, N - i)
        print("(", i, ",",
              N - i, "), ", end = "")
 
# Driver code
if __name__ == "__main__":
     
    N = 5
     
    findPairs(N)
 
# This code is contributed by ajaykr00kj


C#
// C# program for the above approach
using System;
  
class GFG{
  
// Function to print all pairs whose
// sum of Bitwise OR and AND is N
static void findPairs(int N)
{
     
    // Iterate from i = 0 to N
    for(int i = 0; i <= N; i++)
    {
         
        // Print pairs (i, N - i)  
        Console.Write( "(" + i + ", " +
                        (N - i) + "), ");
   }
}
 
// Driver code
public static void Main()
{
    int N = 5;
      
    findPairs(N);
}
}
 
// This code is contributed by sanjoy_62


输出:
(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0),








时间复杂度: O(N)
辅助空间: O(1)