检查数字在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 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短