# LeetCode: Number Of 1 Bits Solution

Shift bit and check

## Approach

Shift bit to the left and check on each shift

## Implementation 1

As

n
is still passed as decimal representation, so keep dividing by 2

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var hammingWeight = function (n) {2  let res = 03  while (n) {4    res += n % 2 === 0 ? 0 : 15    n = Math.floor(n / 2)6  }7  return res8}`

## Implementation 2: Pure bit manipulation

n >>>= 1
is equivalent to
n = Math.floor(n / 2)

n & 1
does the AND operator on every bit, so if
n
is divisible by 2, result would be
0
, else
1

```1n:     101121:     00013n & 1: 0001 -> 14
5n:     101061:     00017n & 1: 0000 -> 0```
`1var hammingWeight = function (n) {2  for (var res = 0; n !== 0; res += n & 1, n >>>= 1) {}3  return res4}`

leetcode

bit manipulation

## Next Post

LeetCode: Best Time To Buy And Sell Stock II

Feb 1, 2021

Search Posts