Loading...
Loading...
A hostel warden controls 32 room lights from one panel. The panel stores the state of all the lights in one Java int: bit i is 1 when light i is on.
The panel shows this number as a normal signed integer, so it can be negative. Print how many lights are on, that is, how many bits of the 32-bit int are 1.
int (32 bits, two's complement form for negatives)Example 1
Input
13
Output
3
13 is 1101 in binary, so three bits are 1.
Example 2
Input
-1
Output
32
In two's complement form, -1 is 32 ones, so every light is on.
Try the problem first. Open one hint at a time.
Look at the lowest bit with n & 1, then move to the next bit.
For a negative n, n >> 1 keeps copying the sign bit, so n never reaches 0. Use >>>, or loop exactly 32 times.
A neat trick: n & (n - 1) clears the lowest 1 bit of n. Count how many times you can do this before n becomes 0.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor