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

1var hammingWeight = function (n) {
2 let res = 0
3 while (n) {
4 res += n % 2 === 0 ? 0 : 1
5 n = Math.floor(n / 2)
6 }
7 return res
8}

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: 1011
21: 0001
3n & 1: 0001 -> 1
4
5n: 1010
61: 0001
7n & 1: 0000 -> 0
1var hammingWeight = function (n) {
2 for (var res = 0; n !== 0; res += n & 1, n >>>= 1) {}
3 return res
4}

Comments

Loading comments...

Tags

leetcode

bit manipulation

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Best Time To Buy And Sell Stock II

Feb 1, 2021

HoningJS

Search Posts