LeetCode-191. Number of 1 Bits

这道题考察的是一个二进制的特性。通过n&(n-1)可以判断n的二进制表示中有几个1.(最开始超时这道题的时候我心中是万马奔腾的) 

// you need to treat n as an unsigned value

public int hammingWeight(int n) { int count=0;while(n!=0) { count++; n = n & (n - 1); } return count; }

开始我的代码:

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

 

posted @ 2016-03-20 16:33  SnailRen  阅读(112)  评论(0编辑  收藏  举报