Power Of Three Problem
Description
LeetCode Problem 326.
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Example 1:
1
2
Input: n = 27
Output: true
Example 2:
1
2
Input: n = 0
Output: false
Example 3:
1
2
Input: n = 9
Output: true
Example 4:
1
2
Input: n = 45
Output: false
Constraints:
- -2^31 <= n <= 2^31 - 1
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool isPowerOfThree(int n) {
if (n == 1)
return true;
if (n <= 0 || n % 3 != 0)
return false;
return isPowerOfThree(double(n) / 3);
}
};