檢查一個數字在 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