【LeetCode刷题记录】Number of 1 Bits

来源:互联网 发布:软件架构设计图 编辑:程序博客网 时间:2024/06/05 07:09

题目:

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.


解法:

题意是求出一个无符号整数的二进制表示中位“1”的个数,也就是这个数的汉明重量(Hamming Weight,翻译成中文有点奇怪)。刚好最近接触到CSAPP中和位运算有关的知识,所以比较容易地想到逐位去统计“1”的个数:从最高位开始,通过移位和与操作得到最高位是0或1,然后累加到计数中。AC代码如下:

int hammingWeight(uint32_t n) {    int i, count = 0;    int bit = 0;//store each bit    for(i=0; i<32; i++) {// from high bit to low bit        bit = n << i;        bit = (bit >> 31) & 1;        count += bit;    }    return count;}

看到讨论区里有人贴出更为精简的解法,思路是"n = n & *(n-1)"。如果大多数的数据位是0的话,这种方法很快速,可能不需要遍历32位。时间复杂度是O(m),m是1的位数(虽然个人以为差别不大,但优化的思路是很好的:-))。代码如下:

int hammingWeight(uint32_t n){    int res = 0;    while(n)    {        n &= n - 1;        ++ res;    }    return res;}


0 0
原创粉丝点击