LeetCode#459 Repeated Substring Pattern

問(wèn)題描述

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?

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

補(bǔ)充說(shuō)明:

這個(gè)題目的要求通過(guò)實(shí)現(xiàn)一個(gè)函數(shù),當(dāng)輸入一個(gè)數(shù)字的時(shí)候,如果這個(gè)數(shù)字是3的冪(次方),則返回True。

另外這里有個(gè)小小的要求,就是在實(shí)現(xiàn)功能的前提下,要求盡量不要用循環(huán)或者遞歸實(shí)現(xiàn)。

方案分析

  1. 首先說(shuō)使用循環(huán)的方式,因?yàn)槭?的冪,肯定滿足的一個(gè)條件就是循環(huán)除以3,肯定有一次能被整除。so easy。上代碼。

python實(shí)現(xiàn)

class Solution(object):
      def isPowerOfThree(self, n):
          """
          :type n: int
          :rtype: bool
          """
          if n<=0:
              return False
          while(n%3==0):
              n = n / 3
          return True if n==1 else False

方案分析2

  1. 既然會(huì)求冪,反過(guò)來(lái)就是求log了,那么使用log函數(shù)去解決這個(gè)問(wèn)題,但是這里有個(gè)問(wèn)題,看注釋部分。

python實(shí)現(xiàn)2

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        import math
        epsilon = 0.000000000000001
        if n <= 0:
            return False
        # return ((math.log(n, 3) + epsilon) % 1 ) <=  2 * epsilon
        # 這塊無(wú)效,java可以用,但是python無(wú)效,應(yīng)該是各自的機(jī)制不同,取決于對(duì)浮點(diǎn)數(shù)除法的精度是多少,可以自行試試?;蛘哂泻玫南敕梢粤粞浴?        return 3 ** round((math.log(n, 3))) == n

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容