📌  相关文章
📜  按位 OR 和按位 AND 之和等于 N 的非负对

📅  最后修改于: 2021-10-27 03:20:14             🧑  作者: 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


Javascript


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

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