This program has three bugs, and all three are classic bit mistakes.
What to build
A correct report on each number, made by repairing the program you are given.
Requirements
- Print
evenorodd, using the lowest bit. - Print how many bits are set.
- Print
powerif the number is a power of two, and otherwiseno.
Input
The first line has q. Each of the next q lines has a number x.
Output
One line per number: the three answers, separated by spaces.
Constraints
1 ≤ q ≤ 100 and 1 ≤ x ≤ 1,000,000,000.
Example
Input:
3
8
7
1
Output:
even 1 power
odd 3 no
odd 1 power
Why it works
& binds less tightly than ==, so x & 1 == 0 means x & (1 == 0), which is always 0. A power of two has exactly one bit set, and subtracting 1 clears that bit and sets all the lower ones, so ANDing them gives 0.
Examples
Example 1 · Input
3 8 7 1
Expected output
even 1 power odd 3 no odd 1 power
Example 2 · Input
1 6
Expected output
even 2 no
Hints
Hint 1
In C, `==` is done before `&`. Add parentheses wherever the two appear together.
Hint 2
To look at every bit, the shift must move by one place each time.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int q;
scanf("%d", &q);
while (q-- > 0) {
int x;
scanf("%d", &x);
if ((x & 1) == 0) printf("even ");
else printf("odd ");
int bits = 0;
for (int v = x; v > 0; v = v >> 1) bits += v & 1;
printf("%d ", bits);
if ((x & (x - 1)) == 0) printf("power\n");
else printf("no\n");
}
return 0;
}