Power of Four

Given an integer n, return true if it is a power of four, and false otherwise. An integer n is a power of four if there is an integer x such that n == 4^x. Follow up: can you solve it without loops or recursion?

30:00

Power of Four
easy
Free written solution
Topics
Companies

Given an integer n, return true if it is a power of four, and false otherwise. An integer n is a power of four if there is an integer x such that n == 4^x. Follow up: can you solve it without loops or recursion?

Example 1:
Input: {"n":16}
Output: true
Constraints:
  • −231≤n≤231−1-2^{31} \leq n \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":16}

Is 16 a power of four? Powers of four are 1, 4, 16, 64, ... and in binary each is a single 1 followed by an even number of 0s.

n = 16

Bits (low 8)

green columns = even positions

7
6
5
4
3
2
1
0
n
n-1
n&(n-1)
mask
n&mask

n > 0

...

n&(n-1) == 0

...

n&mask != 0

...

Variables
VariableValue
n16
DepthFunction Call
Stack empty
0/7