leetcode - Number of 1 Bits

leetcode - Number of 1 Bits

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 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int sum = 0;
 5         while(n!=0){
 6             int tp = n%2;
 7             n /= 2;
 8             sum += tp;
 9         }
10         return sum;
11     }
12 };

 

题目比较白痴…… 终于又可以爽一下了……

 

不过uint32_t 这个数据类型值得注意下:

一些解释:

http://www.cnblogs.com/wwping/articles/2295954.html

http://www.cnblogs.com/wwping/articles/2293898.html

 

update:  用位操作显然更高效。 自己太不熟悉位操作了。要加强。

example:

int hammingWeight(uint32_t n) {
    int count = 0;
    while (n > 0) {
        if (n & 0x1) {
            count++;
        }
        n = n >> 1;
    }
    return count;
}

from: http://blog.csdn.net/booirror/article/details/44218887
原数与1相与,得最后一位,累加求和,原数右移一位,继续循环直到原数变为0. 很简洁。

posted @ 2015-05-12 17:01  cnblogshnj  阅读(126)  评论(0)    收藏  举报