检查一个数字在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP