Problem 191

Posted by Ruizhi Ma on October 27, 2020

Solution URL

https://leetcode.com/submissions/detail/413903225/

代码

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        //ans: https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode/
        int bits = 0;
        int mask = 1;
        for(int i = 0; i < 32; i++){
            if((mask & n) != 0){
                bits++;
            }
            mask = mask << 1;
        }

        return bits;
    }
}