0326. Power of Three
https://leetcode.com/problems/power-of-three
Description
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 == 3x.
Example 1:
**Input:** n = 27
**Output:** trueExample 2:
**Input:** n = 0
**Output:** falseExample 3:
**Input:** n = 9
**Output:** trueExample 4:
**Input:** n = 45
**Output:** falseConstraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
ac1: iterative
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) return false;
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
}ac2: trick
3^19 = 1162261467, the biggest number within Integer range. so n must <= 1162261467.
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) return false;
return 1162261467 % n == 0;
}
}ac3: math
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) return false;
return Math.log10(n) / Math.log10(3) % 1 == 0; // integer
}
}Last updated
Was this helpful?