Gyh's Braindump

CN-15. Number of 1 bits

tags
trick, BinaryOperation
source
leetcode-cn

Edge Cases

Solution 1 - Loop

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

Complexity

  • time: O(log2N)
  • space: O(1)

Solution 2 - Trick

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