LeetCode 326. Power of Three

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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章