LeetCode 191. Number of 1 Bits
Intuition
- Check how many 1 bits are there in the binary representation of
n
. - Using the right shift operation, check whether the last bit of
n
is 1 (by checking whethern
is odd).
Approach
- Initialise
ans
to 0. - While
n
is greater than 0 (i.e., the binary representation contains at least one 1 bit):- Increase
ans
if the last bit ofn
is odd (i.e., the binary representation of n is 1).
- Increase
Pseudocode of hammingWeight()
:
1 | hammingWeight(n): |
Complexity
Time complexity: $O(logn)$.
- $logn$ iterations to calculate how many 1 bits are in the binary representation.
Space complexity: $O(1)$.
Code
1 | class Solution { |