C++ bootcamp · Lab 50

Power of two?

mediumBitwise10 minLesson: Operators

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. Print yes if it is a power of two, else no.

A power of two has exactly one bit set.

Input. One integer n ≥ 1.

Output. yes or no.

Examples

Example 1 — 2^3
Input
8
Output
yes
Example 2
Input
6
Output
no
Hint
  1. n > 0 && (n & (n - 1)) == 0
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>

int main() {
  int n; std::cin >> n;
  std::cout << (n > 0 && (n & (n - 1)) == 0 ? "yes" : "no") << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.