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
nis 1 (by checking whethernis odd).
Approach
- Initialise
ansto 0. - While
nis greater than 0 (i.e., the binary representation contains at least one 1 bit):- Increase
ansif the last bit ofnis 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 { |