编写一个c程序来计算整数中的设置位数?
回答:
1 2 3 4 5 6 7 8 9 10 |
unsigned int NumberSetBits(unsigned int n) { unsigned int CountSetBits= 0; while (n) { CountSetBits += n & 1; n >>= 1; } return CountSetBits; } |
本质上就是计算n中1的和,就是位数了
1 2 3 4 5 6 7 8 9 10 |
unsigned int NumberSetBits(unsigned int n) { unsigned int CountSetBits= 0; while (n) { CountSetBits += n & 1; n >>= 1; } return CountSetBits; } |
本质上就是计算n中1的和,就是位数了