给定一个正整数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)