图片说明

  • 初始版本为这个 但是有个问题就是无法区分负数
    public class Solution {
      // you need to treat n as an unsigned value
      public int hammingWeight(int n) {
           int ans = 0;
           while(n>0) {
              if((n&1)==1) 
                  ans++;
              n>>=1;
           }
          return ans;
      }
    }
  • 改为以下版本 用一个数来跟进每个位的情况 就不会负数>>....=> 0
    public class Solution {
      public int hammingWeight(int n) {
           int ans = 0;
           int flag = 1;
           for(int i = 0 ; i< 32 ;i++) {
               if((n&flag)!=0) 
                   ans++;
               flag<<=1;
           }
           return ans;
       }
    }
    public int hammingWeight(int n) {
      int sum = 0;
      while (n != 0) {
          sum++;
          n &= (n - 1);
      }
      return sum;
    }