求三元组 A、B、C 相互按位或按位与为 K
给定一个整数K ,任务是找到三个不同的整数A、B 和 C使得 ( A ∣ B ) & ( B ∣ C ) & ( C ∣ A ) = K ,其中| &分别表示按位或和按位与运算。如果有多个解决方案,您可以打印其中任何一个。
例子:
Input: K = 3
Output: 1 2 3
Explanation: ( 1 ∣ 2 ) & ( 2 ∣ 3 ) & ( 3 ∣ 1 ) = 3 & 3 & 3 = 3
Input: K = 13
Output: 6 9 13
天真的方法:蛮力方法是运行三个嵌套循环并找到满足上述表达式的所有三个整数。
时间复杂度: O(K 3 )
辅助空间: O(1)
有效的方法:这个问题可以根据以下观察来解决:
Every set bit of K must be present in (A|B), (B|C) and (A|C) which implies that every set bit of K must be present in at least 2 of A, B and C.
So, make two numbers same as K and the other 0. To make the two numbers distinct add a larger power of 2 (which is greater than K) to any of them.
请按照以下步骤解决问题:
- 使 A 和 B 等于 K 和 C = 0。
- 现在将更高的 2 次幂(大于 K)添加到 B [这里使用 2 27 ]。
- 打印 A、B 和 C 的值。
下面是上述方法的实现:
C++
// C++ program to implement the approach
#include
using namespace std;
// Function to print three integers
void printABC(int K)
{
// One of them are equal to zero
// and rest two are equivalent
// to X itself but to make
// A!=B add a larger power of 2 to B
cout << K << " " << K + (1 << 27)
<< " " << 0 << endl;
}
// Driver Code
int main()
{
int K = 3;
// Function call
printABC(K);
return 0;
}
Java
// Java program to implement the approach
import java.io.*;
public class GFG {
// function to print three integers
static void printABC(int K)
{
// One of them are equal to zero
// and rest two are equivalent
// to X itself but to make
// A!=B add a larger power of 2 to B
System.out.println(K + " " + (K + (1 << 27)) + " "
+ 0);
}
// Driver Code
public static void main(String[] args)
{
int K = 3;
// Function Call
printABC(K);
}
}
// This code is contributed by phasing17
Python3
# Python3 program to implement the approach
# function to print three integers
def printABC(K):
# one of them is equal to zero
# and the rest two are equivalent to X
# itself but to make
# A != B add a larger power of 2 to B
print(K, K + (1 << 27), 0)
# Driver Code
K = 3
# Function Call
printABC(K)
# This code is contributed by phasing17
C#
// C# program to implement the approach
using System;
class GFG {
// Function to print three integers
static void printABC(int K)
{
// One of them are equal to zero
// and rest two are equivalent
// to X itself but to make
// A!=B add a larger power of 2 to B
Console.WriteLine(K + " " + (K + (1 << 27)) + " "
+ 0);
}
// Driver Code
public static void Main()
{
int K = 3;
// Function call
printABC(K);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
3 134217731 0
时间复杂度:O(1)
辅助空间:O(1)