Number of 1 Bits
@GrubenM Thanks .very good explaination
Using STL bitset count()
Thanks for the explanation!
You can change the solution:
This doesn't work for something like 0x8000, does it?
No one has replied
Thanks for your brilliant solution and patient illustrations.
In average second approach works works faster.
Ex: n = 9;
With first approach you need 4 iterations to count number of bits, while only 2 iterations with second. Hope that helps
Hey, sure! That should be number of '1's of course.
Good answer! But just want people know that in an real interview the interviewer may ask for another solution that demonstrates algorithmic thinking and ability to handle bitwise operations. Anyway, upvote!
Cannot believe that recursion is actually faster than doing the loop.
Would you explain that why this is faster than simply doing a while loop(which I got 8ms)?
@ahendy oh nope dude, you actually change the question's default function variables from def hammingWeight(self, n) to def hammingWeight(self, n, count=0)
Here is my recursion version:
@999masks n should be an integer like 5, not bits
this code snippet only beats 12.5% of accepted code. How do the others do this? Mine is 2ms too.
declaring the function to take (long n) is allowed ... however OJ testcases still fail.
Actually I got this error:
Input: 2147483648 (10000000000000000000000000000000)
Disabled Categories are greyed out
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.