leetcode刷題筆記326 3的冪


題目描述:

給出一個整數,寫一個函數來確定這個數是不是3的一個冪。

后續挑戰:
你能不使用循環或者遞歸完成本題嗎?

 

題目分析:

既然不使用循環或者遞歸,那我可要抖機靈了

如果某個數n為3的冪 ,則k=log3N

代碼思路:

首先求出int范圍最大的3的冪   Max3

如果n為3的冪,則Max3必定能整除n

so,直接上代碼

 

解答代碼:

C++版:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0)return false;
        const int maxint=0x7fffffff;
        int k=log(maxint)/log(3);
        int b3=pow(3,k);
        return (b3%n==0);
    }
};
Code

Python版:

class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        maxint = 0x7fffffff

        k=math.log(maxint)//math.log(3)
        b3=3**k
        return (b3%n)==0
Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM