Read the question, write C on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read a positive integer n and print yes if it is a power of two, otherwise no.
A power of two has exactly one bit set. The trick: n & (n - 1) is 0 exactly then (and n is not 0).
Input. One integer n ≥ 1.
Output. yes or no.
Constraints
- 1 ≤ n ≤ 1 000 000 000
Examples
Input
8
Output
yes
Input
6
Output
no
Input
1
Output
yes
Hint
- (n & (n - 1)) == 0 detects a single set bit.
- You can also loop dividing by 2 while n is even.
Show correct code
Peek only after you have tried. You can still Check your own version.
#include <stdio.h>
int main(void) {
int n;
if (scanf("%d", &n) == 1) {
int ok = n > 0 && (n & (n - 1)) == 0;
printf(ok ? "yes\n" : "no\n");
}
return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.