{面试题10: 二进制中1的个数}
From 剑指Offer 何海涛 著
#include <iostream> using namespace std; int numberOf1(int n) { unsigned int newN = static_cast<unsigned int>(n); // 强制将 n 转换为一个无符号数, 避免负数左移, 产生死循环 int count = 0; while(newN) { if(newN&1) { count++; } newN >>= 1; } return count; } int NumberOf1(int n) { int count = 0; while(n) { count++; n &= n-1; // 将 n 最右侧的 1 消耗掉 } return count; }
测试集:
void test(int n, int expected) { std::cout << std::boolalpha << (numberOf1(n) == expected) << std::endl; std::cout << std::boolalpha << (NumberOf1(n) == expected) << std::endl; } int main(int argc, char* argv[]) { test(0, 0); test(1, 1); test(10, 2); test(0x7fffffff, 31); test(0xffffffff, 32); test(0x80000000, 1); return 0; }
总结:
1. 判断一个数 n 是否是 2 的幂?
(n != 0) && ((n & (n-1)) == 0)
2. 求不小于 n 的 2 的幂?
if(n>=1) { --n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; ++n; }