LeetCode: Number Of 1 Bits Solution
Shift bit and checkApproach
Shift bit to the left and check on each shift
Implementation 1
As
n
is still passed as decimal representation, so keep dividing by 21var 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 -> 145n: 101061: 00017n & 1: 0000 -> 0
1var hammingWeight = function (n) {2 for (var res = 0; n !== 0; res += n & 1, n >>>= 1) {}3 return res4}
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