剑指offer之二进制中1的个数(Java实现)

版权声明:转载请联系 :[email protected] https://blog.csdn.net/weixin_40928253/article/details/85373225

二进制中1的个数

NowCoder

题目描述:

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

解题思路:

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        int flag = 1;
        while (flag != 0) {
            if ((n & flag) != 0) {
                count++;
            }
            flag = flag << 1;
        }
        return count;
    }
}
public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while (n != 0) {
            ++count;
            n = (n - 1) & n;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40928253/article/details/85373225