C bootcamp · Lab 43

Power of two

mediumBitwise12 minLesson: Bitwise

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

Example 1 — 8 is 2³.
Input
8
Output
yes
Example 2
Input
6
Output
no
Example 3 — 2⁰ = 1.
Input
1
Output
yes
Hint
  1. (n & (n - 1)) == 0 detects a single set bit.
  2. 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.