Skip to content

Latest commit

 

History

History
29 lines (21 loc) · 676 Bytes

number-of-one.md

File metadata and controls

29 lines (21 loc) · 676 Bytes

二进制中1的个数

题目

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

解题思路

  1. 负数是补码表示
  2. >>> 为无符号右移,>>为有符号右移,当 n 为负数是会增加多余的1
public int NumberOf1(int n) {
    int mask = 0x01;

    int res = 0;
    int t = n;
    while (t != 0) {
        if ((t & mask) == 1) {
            res++;
        }
        t = t >>> 1;
    }

    return res;
}