C++ 中二進位制表示中 0 和 1 的異或計數


本題給定一個數字。我們的任務是找出該數字在二進位制表示中 0 和 1 次數的異或值。

我們舉一個例子來理解這個問題,

輸入

n = 9

輸出

0

解釋

binary = 1001
Count of 0s = 2
Count of 1s = 2
2 ^ 2 = 0

為了解決這個問題,我們將首先將數字轉換為其二進位制等價,然後遍歷數字的每個二進位制位,計算 0 和 1 的次數,然後再找出 0 和 1 的次數的異或值。

以下示例程式演示了上述解決方案,

示例

 即時演示

#include<iostream>
using namespace std;
int countXOR10(int n) {
   int count0s = 0, count1s = 0;
   while (n){
      (n % 2 == 0) ? count0s++ :count1s++;
      n /= 2;
   }
   return (count0s ^ count1s);
}
int main() {
   int n = 21;
   cout<<"XOR of count of 0s and 1s in binary of "<<n<<" is "<<countXOR10(n);
   return 0;
}

輸出

XOR of count of 0s and 1s in binary of 21 is 1

更新於: 17-4-2020

162 次瀏覽

開啟你職業生涯

透過完成課程獲得認證

開始
廣告