Coders Crushby Napplied AI
Back to DSA Problems
EasyBit Manipulation

Number of 1 Bits

Count 1 bits in integer

Solution Approach

Count set bits using bitwise operations. Check LSB and right shift, or use n & (n-1) trick.

Implementation
def hammingWeight(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count
    
# Using bit trick
def hammingWeightTrick(n):
    count = 0
    while n:
        n &= n - 1  # Remove rightmost 1 bit
        count += 1
    return count
Complexity Analysis

Time Complexity

O(1)

Space Complexity

O(1)
Complexity
Time:O(1)
Space:O(1)
Asked at
GoogleMicrosoft
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless