Loading…
Loading…
Given an integer, count how many of its binary bits are set to 1 (its "Hamming weight").
Input: 11 (binary 1011)
Output: 3
Repeatedly check the lowest bit with n & 1, add it to a running count, then right-shift n by one bit to check the next one. Stop once n becomes 0. This runs in O(number of bits) time — for a 32-bit integer, at most 32 iterations.
1count = 0
2while n:
3 count += n & 1
4 n >>= 1
5print(count)Line 1: a single non-negative integer n
Print the number of set bits.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.
No discussions yet
Be the first to start a conversation.