今天继续刷LeetCode,第326题,判断一个数是否是3的阶乘。
分析:
方法一:递归,不断对n进行除3操作,判断结果是否为1;
方法二:循环,
问题:
1、递归需要利用栈;
附上C++代码:
class Solution {
public:
bool isPowerOfThree(int n) {
if(n<=0)
return false;
if(n==1)
return true;
if(n%3==0)
return isPowerOfThree(n/3);
else
return false;
}
};
附上Python代码:
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n<1:
return False
while n%3==0:
n/=3
return n==1