问题:给定一个无符号整型的对象,统计其二进制序列中1的个数?
遍历:
unsigned bit_count(unsigned x) { unsigned result=0; while(x){ result+=x&01?1:0; x>>=1; } return result; }
位运算:
unsigned bit_count_2(unsigned x) { unsigned result=0; while(x){ ++result; x&=(x-1); //去除从右往左数出现的第一个1 } return result; }