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;

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