https://leetcode.com/problems/power-of-three/
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
1、一直整除3,直至最终为1,且无余数(136ms)
class Solution {
public:
bool isPowerOfThree(int n) {
if(n == 1)
return true;
while(n/3!=0){
if(n%3 != 0)
return false;
if(n/3 == 1)
return true;
n /= 3;
}
return false;
}
};
简洁:
class Solution {
public:
bool isPowerOfThree(int n) {
while(n != 0 && n%3 == 0){
n /= 3;
}
if(n == 1)
return true;
return false;
}
};
2、网上看到以下一种方法,技巧性,1162261467 = 3^19, 3^20 is bigger than int. (132ms)
class Solution {
public:bool isPowerOfThree(int n) {
return (n>0 && 1162261467%n == 0);
}
};