兩個整數二進位制表示中不匹配的位數


二進位制語言是計算機的語言。因此,每個整數、字元或符號都需要轉換為二進位制系統,反之亦然。所有高階語言都有二進位制表示。在本文中,我們將討論整數的二進位制表示。此外,我們將找到兩個整數二進位制表示中不匹配的位。

輸入輸出場景

給定兩個整數 X 和 Y。其二進位制表示中不匹配的位數作為輸出。

Input: X = 25, Y = 15
Output: 3
Input: X = 6, X = 19
Output: 3

對於 X = 25,Y = 15,25 的二進位制表示為 11001,15 的二進位制表示為 1111。不匹配的位數為 3。

使用 for 迴圈和移位位置

我們將使用 for 迴圈遍歷整數的位。迴圈將從 **0** 迭代到 **32**,因為在現代計算機中,**int** 資料型別使用 32 位表示。

在 for 迴圈中,我們將檢查兩個整數所有位置的位,並找出第 **ith** 位是否相同或不同。如果不同,我們將計數變數增加 1。

示例

以下示例計算兩個整數二進位制表示中不匹配的位數:

#include <iostream>
using namespace std;
int number(int A, int B){
   int count = 0;
   for (int i = 0; i < 32; i++) {
      if ((A & (1 << i)) != (B & (1 << i))) {
         count++;
      }
   }
   return count;
}
int main(){
   int A = 6, B = 19;
   cout<< "Number of mismatching bits in binary representation of "<< A << " and " << B << " is " << number(A, B) << std::endl;
   return 0;
}

輸出

Number of mismatching bits in binary representation of 6 and 19 is 3

使用 XOR 運算

我們將對兩個整數使用 **XOR** 運算。**XOR** 運算檢查整數在相同位置的位是否不同。如果相同,結果為 0。而如果不同,結果為 1。此結果儲存在 x 變數中。這將儲存兩個整數的所有不匹配位(為 1)。

接下來,我們執行一個 while 迴圈,直到 x 的值為非零。在迴圈中,我們使用 **AND** 運算子檢查最高有效位(通常是最左邊的位)是否為 1。如果為 1,則計數變數增加 1。

然後,我們使用 **(x >>= 1)** 將最高有效位向右移動一位。這使我們能夠計算不匹配位的總數。

示例

讓我們看一個例子:

#include <iostream>
using namespace std;
int number(int A, int B){
   int x = A ^ B;
   int count = 0;
   while(x > 0){
      if(x & 1){
         count++;
      }
      x >>= 1;
   }
   return count;
}
int main(){
   int A = 116, B = 219;
   cout<< "Number of mismatching bits in binary representation of "<< A << " and " << B << " is " << number(A, B) << std::endl;
   return 0;
}

輸出

Number of mismatching bits in binary representation of 116 and 219 is 6

使用 Bitset 類

我們將使用標準 C++ 庫的 **bitset** 類。它用於建立一個包含指定整數二進位制表示的物件。

std::bitset<32> name(integer);

接下來,我們對這兩個物件執行 **XOR** 運算。此運算給出兩個整數二進位制表示中不同的位。然後,我們使用 **count()** 函式計算不匹配位的總數。

示例

以下示例使用 bitset 類計算不匹配的位數:

#include <iostream>
#include <bitset>
using namespace std;
int number(int A, int B){
   std::bitset<32> num1(A);
   std::bitset<32> num2(B);
   std::bitset<32> result = num1 ^ num2;
   return result.count();
}
int main(){
   int A = 89, B = 72;
   cout<< "Number of mismatching bits in binary representation of "<< A << " and " << B << " is " << number(A, B) << std::endl;
   return 0;
}

輸出

Number of mismatching bits in binary representation of 89 and 72 is 2

結論

我們討論了查詢兩個整數二進位制表示中不匹配位數的不同方法。第一種方法是使用 for 迴圈遍歷整數的位。第二種方法是對整數使用 **XOR** 運算。第三種方法是使用 C++ 庫的 **bitset** 類。

更新於: 2024年1月5日

249 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告