• 问题:给定一个整数,如何判断该整数的二进制表示里有多少个1。
  • 现实用途:应该可以用于数据的校验。

解法(c++):

#include <iostream>
#include <assert.h>

using namespace std;

// 求解x的二进制表示里有多少个1的算法。
// x = x & (x -1); 每次消掉一个1.
int get_one_bit_count(int x) {
    int count = 0;
    while(x){
        count ++;
        x = x & (x - 1);
    }
    return count;
}

// 用例测试
int main() {
    assert(get_one_bit_count(32) == 1);
    assert(get_one_bit_count(15) == 4);
    assert(get_one_bit_count(7) == 3);
    assert(get_one_bit_count(0) == 0);
    return 0;
}

2015-03-13 Fri

相关文章:

  • 2021-09-21
  • 2021-06-21
  • 2021-12-16
  • 2021-11-08
  • 2021-12-05
  • 2021-12-04
  • 2022-12-23
猜你喜欢
  • 2021-07-23
  • 2022-01-24
  • 2021-07-31
  • 2021-10-19
  • 2021-10-19
  • 2022-02-23
  • 2022-12-23
相关资源
相似解决方案