Power of Three

Given an integer n, return true if it is a power of three, meaning there is an integer x with n == 3^x. Otherwise return false. Follow up: can you solve it without loops or recursion?

30:00

Power of Three
easy
Free written solution
Topics
Companies

Given an integer n, return true if it is a power of three, meaning there is an integer x with n == 3^x. Otherwise return false. Follow up: can you solve it without loops or recursion?

Example 1:
Input: {"n":27}
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":27}

The slow way: divide 27 by 3 while the remainder is 0. A power of three shrinks all the way to 1.

peel off factors of 3 (the slow way)

27

the 20 powers of three that fit in an int

3^0

1

3^1

3

3^2

9

3^3

27

3^4

81

3^5

243

3^6

729

3^7

2187

3^8

6561

3^9

19683

3^10

59049

3^11

177147

3^12

531441

3^13

1594323

3^14

4782969

3^15

14348907

3^16

43046721

3^17

129140163

3^18

387420489

3^19

1162261467

loop-free check

n > 0 ?
3^19 = 1162261467 = 3 × 3 × … × 3 (19 threes)
1162261467 % 27 = ?
Variables
VariableValue
n27
DepthFunction Call
Stack empty
0/8