检查数字在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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短