Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Number of 1 Bits

LeetCode #191Easy
Hamming weight · n & (n − 1)

Given an unsigned integer n, return the number of set bits (its Hamming weight).

Asked atAmazonAppleMicrosoft
step 1 / 12
1
0
1
1
[0][1][2][3]
Check each bit
1count ← 0
2for i in 0..width-1:
3 count += (n >> i) & 1
4return count
state
  • n11
  • binary1011
  • count0

line 1n = 11 = 1011. The "Hamming weight" is just how many bits are 1. Simplest plan: look at every bit position, one at a time, and tally the 1s. Start count = 0.