给定一个正整数N,任务是找到这样所有非负对(A,B),其按位或和按位的AND A的总和,B等于N,即,(A | B)+(A& B)= N。
例子:
Input: N = 5
Output: (0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)
Explanation: All possible pairs satisfying the necessary conditions:
- (0 | 5) + (0 & 5) = 5 + 0 = 5
- (1 | 4) + (1 & 4) = 5 + 0 = 5
- (2 | 3) + (2 & 3) = 3 + 2 = 5
- (3 | 2) + (3 & 2) = 3 + 2 = 5
- (4 | 1) + (4 & 1) = 5 + 0 = 5
- (5 | 0) + (5 & 0) = 5 + 0 = 5
Input: N = 7
Output: (0, 7), (1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)
Explanation: All possible pairs satisfying the necessary conditions:
- (0 | 7) + (0 & 7) = 7 + 0 =7
- (1 | 6) + (1 & 6) = 7 + 0 =7
- (2 | 5) + (2 & 5) = 7 + 0 =7
- (3 | 4) + (3 & 4) = 7 + 0 =7
- (4 | 3) + (4 & 3) = 7 + 0 =7
- (5 | 2) + (5 & 2) = 7 + 0 =7
- (6 | 1) + (6 & 1) = 7 + 0 = 7
- (7 | 0) + (7 & 0) = 7 + 0 = 7
天真的方法:最简单的方法是在[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)