Write a function that takes an unsigned integer and returns the number of ’1′ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11′ has binary representation
00000000000000000000000000001011
, so the function should return 3.
Analysis:
We need to check each bit of the integer. To do that, we have a mask and let mask start from 1, which is 0000 0000 0000 0000 0000 0000 0000 0001, then use a logical AND between the number and the mask. If the result is not 0, then that means the digit is 1. Then we shift the mask to left by one.
Time complexity: O(1)
Space complexity: O(1)
Code is below:
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { // O(1) int count = 0; int mask = 1; // Have a mask from 1, 0000 0000 0000 0000 0000 0000 0000 0001 // Use logial AND to check it // Shift the mask left by 1 for (int i = 0; i < 32; i++) { if ((n & mask) != 0) { count++; } mask <<= 1; } return count; } }