Skip to content

Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of 1 bits (Hamming weight).

You need to solve this problem efficiently.

InputOutputExplanation
Example 1Result 1Explanation for example 1
Example 2Result 2Explanation for example 2
  • Constraint 1 for Number of 1 Bits
  • Constraint 2
  • Constraint 3
ApproachTimeSpaceBest When
LoopO(n)O(1)When applicable
KernighanO(n)O(1)When applicable
BuiltinO(n)O(1)When applicable
★ Recommended

This approach provides an efficient solution for number of 1 bits.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
number_of_1_bits_loop.py
def number_of_1_bits_loop(n: int) -> int:
"""Count 1 bits by checking each bit."""
count = 0
while n:
count += n & 1
n >>= 1
return count
# Test cases
print(number_of_1_bits_loop(11)) # 3
print(number_of_1_bits_loop(128)) # 1
🎯 Interview Favourite

This approach provides an efficient solution for number of 1 bits.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
number_of_1_bits_kernighan.py
# Python Solution
# Problem: number-of-1-bits
# Approach: kernighan
# Implementation placeholder for number_of_1_bits_kernighan
# This file is auto-generated and should contain the solution code.
def number_of_1_bits_kernighan():
pass
if __name__ == "__main__":
pass
✓ Simple

This approach provides an efficient solution for number of 1 bits.

⏱ Time O(n) Single pass 💾 Space O(1) Minimal storage
number_of_1_bits_builtin.py
# Python Solution
# Problem: number-of-1-bits
# Approach: builtin
# Implementation placeholder for number_of_1_bits_builtin
# This file is auto-generated and should contain the solution code.
def number_of_1_bits_builtin():
pass
if __name__ == "__main__":
pass