Come from : [https://leetcode-cn.com/problems/power-of-three/]
326. Power of Three
1.Question
Given an integer, write a function to determine if it is a power of three.
Example 1 :
Input: 27
Output: true
Example 2 :
Input: 0
Output: false
Example 3 :
Input: 9
Output: true
Example 4 :
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
2.Answer
easy类型题目。。。
AC代码如下(简单循环):
class Solution {
public:
bool isPowerOfThree(int n) {
if(n<=0) return false;
if(n==1) return true;
while(n>1)
{
if(n%3 != 0) return false;
n = n/3;
}
return true;
}
};
3.大神解答
方法1:递归
class Solution {
public:
bool isPowerOfThree(int n) {
if(n==1) return true;
else if(n==0) return false;
else return isPowerOfThree(n/3) && n%3 == 0;
}
};
方法2:不用循环或递归的做法
3的幂次质因子只有3,而整数范围内的3的幂次最大是1162261467
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467%n == 0;
}
};
作者:gpe3DBjDS1
链接:https://leetcode-cn.com/problems/two-sum/solution/3de-mi-by-gpe3dbjds1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
4.我的收获
fighting。。。
2019/7/5 胡云层 于南京 115