Count Set Bits / Reverse Bits
Problem Two related bit-manipulation tasks. First, count the number of set (1) bits in an integer (the Hamming weight). Second, reverse the bits of a 32-bit unsigned integer so the least-significant bit becomes the most-significant and vice versa.
Input / Output
- Input: a 32-bit unsigned integer
n. - Output: for the first task, the count of 1-bits; for the second, the integer whose bit pattern is the reverse of
n.
Constraints
nis a 32-bit unsigned integer.- Aim for time better than a naive 32-iteration scan where possible, and discuss a constant-time lookup-table variant.
Example
countBits(0b1011)->3reverse(0b00000000000000000000000000000001)->0b10000000000000000000000000000000
added …