您的位置:首页 > 其它

LeetCode 326. Power of Three

2017-09-03 09:43 453 查看

326. Power of Three

Description

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?


Solution

题意即判断一个数是不是3的次方。

和之前的2、4次方不同,不能使用位运算来免除循环,但是我们发现,如果一个数是3的次方,那么在范围内最大的3的次方的数被这个数除,余数一定为0,而倘若不是3的次方,则余数不会为0,这个最大的数就是1162261467,在int范围内,可以通过写一个小循环快速找到。代码如下:

// C++/C
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};


# python
class Solution(object):
def isPowerOfThree(self, n):
return n > 0 and 1162261467 % n == 0;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode