检查数字在C ++中是否具有相同的置位和未置位位数

在本节中,我们将检查数字是否具有相同的置位位数和未置位位数。假设数字12在那。它的二进制表示是1100。它具有相同的0和1。

该方法很简单。我们将检查数字的每一位,如果为1,则增加set_bit_count,如果为0,则增加unset_bit_count。最后,如果它们相同,则返回true,否则返回false。

示例

#include <iostream>
using namespace std;
bool hasSameSetUnset(int n) {
   int set_count = 0, unset_count = 0;
   while(n){
      if((n & 1) == 1){
         set_count++;
      }else{
         unset_count++;
      }
      n = n >> 1; //shift to right
   }
   if(set_count == unset_count)
   return true;
   return false;
}
int main() {
   int num = 35; //100011
   if(hasSameSetUnset(num)){
      cout << "Has same set, unset bits";
   }else{
      cout << "Not same number of set, unset bits";
   }
}

输出结果

Has same set, unset bits