二进制数中1的个数
(1)用整型数据相除等特点,整除的余数来判断
#include <iostream> #include <windows.h> using namespace std; int Count(BYTE i) { int num=0; while (i) { if (1==i%2) { ++num; } i/=2; } return num; } int main() { BYTE i=12; cout<<Count(i)<<endl; return 0; }
(2)通过与0x01做与运算
#include <iostream> #include <windows.h> using namespace std; int Count(BYTE i) { int num=0; while (i) { num+=i & 0x01; i = i >> 1; } return num; } int main() { BYTE i=12; cout<<Count(i)<<endl; return 0; }
(3)做i & i-1 每次都移动一个1位
#include <iostream> #include <windows.h> using namespace std; int Count(BYTE i) { int num=0; while (i) { i&=i-1; ++num; } return num; } int main() { BYTE i=12; cout<<Count(i)<<endl; return 0; }