Problem · Bit Manipulation

Power of Two Without Division

Learn this problem
EasyArm logoArmINTERNPHONE SCREEN

Problem statement

Given a signed integer n, determine whether it is a positive power of two.

A positive integer is a power of two when it can be written as 2^k for an integer k >= 0. Your solution must not use division or a library exponentiation helper such as Math.pow.

Return true when n is a power of two and false otherwise.

Function

isPowerOfTwo(n: int) → boolean

Examples

Example 1

n = 16return = true

16 = 2^4, so the result is true.

Example 2

n = 18return = false

18 is positive but cannot be written as a single power of two.

Example 3

n = 1return = true

1 = 2^0, so it is a power of two.

Constraints

  • -2^31 <= n <= 2^31 - 1.
  • 1 counts as a power of two.
  • Every value less than or equal to 0 returns false.
  • The solution must not use division or a library exponentiation helper.
drafts saved locally
public boolean isPowerOfTwo(int n) {
    // write your code here
}
n16
expectedtrue
checking account