Leetcode 191 Number of 1 Bits 位运算

统计一个值的二进制1的个数,用与(&)和向左移位(<<)

编程之美中的2.1节有详细解答。

解法一:

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int ans = 0;
 5         for(;n;n = n>>1){
 6             ans += n&1;
 7         }
 8         return ans;
 9     }
10 };

解法二:

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int ans = 0;
 5         for(;n;n &=(n-1)){
 6             ans ++;
 7         }
 8         return ans;
 9     }
10 };

 

posted @ 2016-01-24 21:25  Breeze0806  阅读(155)  评论(0编辑  收藏  举报