题目描述:
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?
判断一个数是否为3的幂,不能使用循环或者递归,可以利用log函数,如果结果为整数,说明这个数是3的幂。
class Solution {
public:
bool isPowerOfThree(int n) {
if(n<=0) return false;
double x=log10(n)/log10(3);
if(ceil(x)==floor(x)) return true;
else return false;
}
};
本文介绍了一种不使用循环或递归的方法来判断一个整数是否为3的幂。通过利用对数函数log,如果对数结果为整数,则该数为3的幂。代码实现采用C++,并提供了一个具体的解决方案。
810

被折叠的 条评论
为什么被折叠?



