📜  具有最小差异的最小整数对,其按位异或为 N

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

具有最小差异的最小整数对,其按位异或为 N

给定一个正整数N ,任务是找到两个最小的整数AB ,使得 A 和B的按位异或为N ,并且AB之间差最小。

例子:

朴素方法:解决给定问题的最简单方法是生成范围[0, N]内所有可能的数字对,并打印这对数字,其按位异或是给定数字N并且两个数字都是最小的。

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

有效的方法:上述方法也可以基于以下观察进行优化:

  • 考虑任何数字的二进制表示是“1100011” ,然后该数字可以围绕它们的最高有效位(MSB)拆分为“1000000”“100011” ,并且这些数字的按位异或是给定的数字。
  • 从上面的拆分可以看出, “1000000” (比如A )和“100011” (比如B )组成的数字最小,它们之间的差异最小,因为B形成的值总是更小和最接近到A

根据以上观察,满足给定标准的AB的最小值是将给定数N围绕其最高有效位 (MSB)拆分。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the numbers A and
// B whose Bitwise XOR is N and the
// difference between them is minimum
void findAandB(int N)
{
 
    // Find the MSB of the N
    int K = log2(N);
 
    // Find the value of B
    int B = (1 << K);
 
    // Find the value of A
    int A = B ^ N;
 
    // Print the result
    cout << A << ' ' << B;
}
 
// Driver Code
int main()
{
 
    int N = 26;
    findAandB(N);
 
    return 0;
}


Java
// Java program for the above approach
public class MyClass
{
   
// Function to find the numbers A and
// B whose Bitwise XOR is N and the
// difference between them is minimum
static void findAandB(int N)
{
 
    // Find the MSB of the N
    int K = (int)(Math.log(N) / Math.log(2));
 
    // Find the value of B
    int B = (1 << K);
 
    // Find the value of A
    int A = B ^ N;
 
    // Print the result
    System.out.println(A + " " + B);
}
 
    public static void main(String args[]) {
      int N = 26;
      findAandB(N);
 
    }
}
 
// This code is contributed by SoumikMondal


Python3
# Python3 program for the above approach
from math import log2
 
# Function to find the numbers A and
# B whose Bitwise XOR is N and the
# difference between them is minimum
def findAandB(N):
     
    # Find the MSB of the N
    K = int(log2(N))
 
    # Find the value of B
    B = (1 << K)
 
    # Find the value of A
    A = B ^ N
 
    # Print the result
    print(A, B)
 
# Driver Code
if __name__ == '__main__':
     
    N = 26
     
    findAandB(N)
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the numbers A and
// B whose Bitwise XOR is N and the
// difference between them is minimum
static void findAandB(int N)
{
     
    // Find the MSB of the N
    int K = (int)(Math.Log(N) /
                  Math.Log(2));
 
    // Find the value of B
    int B = (1 << K);
 
    // Find the value of A
    int A = B ^ N;
 
    // Print the result
    Console.Write(A + " " + B);
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 26;
     
    findAandB(N);
}
}
 
// This code is contributed by sanjoy_62


Javascript


输出:
10 16

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