LeetCode 191. Number of 1 Bits Question

题意:给你一个整数,计算该整数的二进制形式里有多少个“1”。比如6(110),就有2个“1”。

 

一开始我就把数字n不断右移,然后判定最右位是否为1,是就cnt++,否则就继续右移直到n为0。

可是题目说了是无符号整数,所以给了2147483648,就WA了。

因为java里的int默认当做有符号数来操作,而2147483648超过int的最大整数,所以在int里面其实是当做-1来计算的。

那么,不能在while里面判断n是否大于0,和使用位操作符>>。应该使用位操作符>>>,这个操作符是对无符号数进行右移的。

 

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        for(int i = 0; i < 32; i++) {
            if( ((n>>>i)&1) == 1 ) cnt++;
        }
        return cnt;
    }
}

 

posted @ 2016-09-24 09:34  sevenun  阅读(121)  评论(0编辑  收藏  举报