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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Show Similar Problems
https://leetcode.com/discuss/78532/summary-all-solutions-new-method-included-at-15-30pm-jan-8th
两种直观解法,上面的链接里还有很多好玩的解法。
递归求解
//recursive
class Solution {
public:
bool isPowerOfThree(int n) {
return n> 0 && ((n == 1) ||((n%3 == 0) && (isPowerOfThree(n/3))));
}
};
迭代求解
首先判断n是否能被3整除,如果可以,就将它除以3。
反复进行这个过程。
如果n是3的幂,那么最后结果一定是1。
//iterative
class Solution {
public:
bool isPowerOfThree(int n) {
if(n >1)
while(n%3 == 0)
n /= 3;
return n == 1;
}
};