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 countComplexity Analysis
Time Complexity
O(1)Space Complexity
O(1)Complexity
Time:O(1)
Space:O(1)
Asked at
GoogleMicrosoft