191. Number of 1 Bits

time: O(1)

space: O(1)

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) { // ๆฏๆฌก้ƒฝ็œ‹ๆœ€ๅณ้‚Š็š„ๆ˜ฏๅฆ็‚บ1
        int count = 0;
        for (int i = 0; i < 32; i++) {
            count += n & 1;
            n = n >> 1;
        }
        return count;
    }
}

optimized

time: O(k), k is the binary length of this num

space: O(1)

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

Last updated