📌  相关文章
📜  求三元组 A、B、C 相互按位或按位与为 K

📅  最后修改于: 2022-05-13 01:56:05.686000             🧑  作者: Mango

求三元组 A、B、C 相互按位或按位与为 K

给定一个整数K ,任务是找到三个不同的整数A、B 和 C使得 ( AB ) & ( BC ) & ( CA ) = K ,其中| &分别表示按位和按位运算。如果有多个解决方案,您可以打印其中任何一个。

例子

天真的方法:蛮力方法是运行三个嵌套循环并找到满足上述表达式的所有三个整数。

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

有效的方法:这个问题可以根据以下观察来解决:

请按照以下步骤解决问题:

  • 使 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)