题意:给你一个整数,计算该整数的二进制形式里有多少个“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;
    }
}

 

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2021-10-29
  • 2022-01-22
  • 2021-10-28
  • 2021-08-17
  • 2021-05-19
  • 2021-08-30
猜你喜欢
  • 2022-01-09
  • 2022-01-11
  • 2022-03-07
  • 2021-06-16
  • 2021-12-04
相关资源
相似解决方案