C++ 使两个数的二进制表示长度相等后对它们进行异或运算

C++ 使两个数的二进制表示长度相等后对它们进行异或运算

异或运算(XOR,exclusive OR)是一种布尔逻辑运算,用于生成奇偶校验位、容错等。可以使用不同的符号来表示这种运算:^、⊕、⊻等。

异或逻辑

只有在两个参数不相同时,异或运算才为真。这意味着相同位的异或结果是0,不同位的异或结果是1。

相同位 −

0 ^ 0 = 0

1 ^ 1 = 0

不同位 −

0 ^ 1 = 1

1 ^ 0 = 1

问题陈述

给定两个数字a和b,找出它们在使它们的二进制表示长度相等后的异或结果。

提示 − 将较小的数字后面添加尾随的零,使二进制表示变得相等。

示例

输入 −

a = 10,b = 5

输出 −

0

解释

10的二进制表示为1010,5的二进制表示为101。

将5后面添加一个尾随零使其变为1010。

因此,1010^1010的异或结果为0。

因此,输出为0。

输入

a = 15,b = 8

输出

7

解释

15的二进制表示为1111,8的二进制表示为1000。

由于两个二进制表示的长度相等,不需要添加尾随零。

1111^1000的异或结果为0111,即十进制表示为7。因此,输出为7。

输入

a = 15,b = 3

输出

7

解释

15的二进制表示为1111,3的二进制表示为11。在给3的二进制表示后添加尾随零后,变为1100。

1111^1100的异或结果为0011。

0011为十进制表示的3。因此,输出为3。

方法

  • 统计两个数字中的位数。

  • 位数可以通过将数字右移直到为零,并计算循环执行的次数来统计。将一个数字右移1位相当于将其除以2。

  • 如果较小数字的位数较小,则执行左移操作,如下所示:smaller_number << (超过的位数)。这将在较小数字后面添加与超过的位数相等的尾零。现在两个数字的位数相等。

  • 对两个数字执行异或操作以获得答案并打印出来。

伪代码

main()
Initialize a -> 15  and  b -> 3.
Function call find_xor(a,b);

find_xor(int a, int b):
c -> minimum of a and b.
d -> maximum of a and b.
count_c -> bit_count(c)
count_d ->bit_count(d)
If count_c < cound_d, then:
c -> c << (count_d - count_c)
Return c XOR d.

bit_count(int x):
count -> 0
while(x != 0):
    Increase the count by one.
    Right shift x by 1, i.e., divide it by 2.
Return x.

示例

下面是一个C++程序,用于计算两个数字的异或运算结果,使得它们的二进制表示长度相等。

#include <bits/stdc++.h>
using namespace std;
// Function to count the number of bits in binary representation
// of an integer
int bit_count(int x){
   //Initialize count as zero
   int count = 0;
   //Count the bits till x becomes zero.
   while (x)    {
      //Incrementing the count
      count++;
      // right shift x by 1
      // i.e, divide by 2
      x = x>>1;
   }
   return count;
}
//Function to find the XOR of two numbers. Trailing zeros are added to the number having a lesser number of bits to make the bits in both numbers equal.
int find_xor(int a, int b){
   //Store the minimum and maximum of both the numbers
   int c = min(a,b);
   int d = max(a,b);
   //Store the number of bits in both numbers.
   int count_c = bit_count(c);
   int count_d = bit_count(d);
   //If the number of bits in c is less, left shift if by the number of exceeding bits.
   if (count_c < count_d){
      c = c << ( count_d - count_c);
   }
   return (c^d);
}
//Driver code
int main(){
   //Initialize a and b.
   int a = 15, b = 3;
   cout << "a = 15, b = 3" << endl;
   //Store the XOR of both the numbers after required computations
   //Function call
   int ans = find_xor(a,b);
   //Print the final result
   cout << "XOR of a and b: "<<ans<<endl;
   return 0;
}

输出

a = 15, b = 3
XOR of a and b: 3

分析

时间复杂度 - O(log n) [对数]

时间复杂度是对数级别的,因为在count函数中有一个while循环。

由于将数字除以2直到变为零,复杂度就变为以2为底的对数。

空间复杂度 - O(1) [常数]

空间复杂度是常数的,因为程序没有使用额外的空间。

结论

在本文中,我们讨论了在使两个数字的二进制表示的长度相等后计算其异或的问题。

我们讨论了异或的概念,然后通过示例和方法进行了讨论。该方法使用了尾部零来使二进制表示的位数相等。我们还看到了该问题的伪代码和C++程序。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程