检查数字在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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿