What is unsigned integer?

Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.

Thinking process

at most there are 32 bits.

then check each bit whether it is 1

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        for (int i = 0; i < 32; ++i) {
            if ((n & (1 << i)) != 0) res++;
        }

        return res;
    }
}

results matching ""

    No results matching ""