LeetCode-326. Power of Threehttps://leetcode.com/problems/power-of-three/
题目描述
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: true
Example 2:
Input: n = 0 Output: false
Example 3:
Input: n = 9 Output: true
Constraints:
-2^31 <= n <= 2^31 - 1
解题思路
【C++】
1. 对数为整
class Solution {
public:
bool isPowerOfThree(int n) {
return fmod(log10(n) / log10(3), 1) == 0;
}
};
2. 除3余数为零
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};
【Java】
class Solution {
public boolean isPowerOfThree(int n) {
int x = 1;
double y = (double) n;
if (n == 1) {return true;}
while (y > x) {y = y / 3;}
if (y == x) {return true;}
else {return false;}
}
}