算法:二进制中1的个数

题目描述:

请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。

例:

输入:00000000000000000000000000001011 
输出:3 
解释:输入的二进制串 00000000000000000000000000001011中,共有三位为 '1'。 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof

思路1: 一个数结尾是1,那么他&1就是1,如果他的结尾是0,那么&1就是0;

就有:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while (n != 0) {
            res += n & 1;
            n = n >>> 1;
        }
        return res;
    }  
}

思路2:

一个数n & (n -1) 可以消除掉最右边的1:
就有:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while (n != 0) {
            res ++;
            n = n & (n -1);
        }
        return res;
    }  
}
原文地址:https://www.cnblogs.com/lijunyzzZ/p/14225084.html