Leetcode 191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
0
which has zero ‘1’ bits.Here’s the Java code to solve the problem:
public class Solution {
// Function to count the number of 1 bits
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += (n & 1); // increment count if the least significant bit is 1
n = n >>> 1; // unsigned right shift operator
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
int n1 = 0b00000000000000000000000000001011; // Binary literal for ease of testing
int n2 = 0b00000000000000000000000010000000;
int n3 = 0b11111111111111111111111111111101;
System.out.println(sol.hammingWeight(n1)); // Output: 3
System.out.println(sol.hammingWeight(n2)); // Output: 1
System.out.println(sol.hammingWeight(n3)); // Output: 31
}
}
(n & 1)
isolates the least significant bit. If it’s 1
, we increment the counter.>>>
) to discard the least significant bit each time.The time complexity of the provided solution is O(1).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?