Power of Two

EasyBit Manipulationbit trick

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer n, determine whether it is a power of two. An integer is a power of two if there exists some non-negative integer exponent x such that n == 2^x. In other words, the value can be written as 1, 2, 4, 8, 16, and so on. Return true if n is a power of two, and false otherwise. Note that zero and any negative integer are never powers of two, since 2^x is always a positive value for every valid exponent. Aim for a solution that runs in constant time using a single bitwise observation: a positive power of two has exactly one bit set in its binary representation.

Examples

Input: n = 1
Output: true
1 equals 2^0, so it is a power of two.
Input: n = 16
Output: true
16 equals 2^4. In binary it is 10000, which has a single set bit.
Input: n = 18
Output: false
18 in binary is 10010, which has two set bits, so it cannot be a power of two.

Constraints

  • -2^31 <= n <= 2^31 - 1
  • The result must be computed in O(1) time and O(1) extra space.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.