iT邦幫忙

0

leetcode with python:342. Power of Four

  • 分享至 

  • xImage
  •  

題目:

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4^x.

給定一數,判斷它是否是4的次方

這題除了底數換成4,跟231.326.根本一模一樣
怎麼這類類題那麼多

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        if n<=0: #0和負數不在討論範圍
            return False
        while n%4==0:
            n=n//4
        return n==1

將一數不斷除四直到不能整除
看最後結果是不是1,就知道該數是不是4的次方了
最後執行時間30ms(faster than 96.05%)

一樣也可以import math用log下去解

import math
class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        if n<=0: #0和負數不在討論範圍
            return False
            
        return (math.log10(n)/math.log10(4))%1==0

透過log的性質,我們可以知道log4(4的次方數)會是整數
且log10(n)/log10(4)=log4(n)
所以我們只要計算log10(n)/log10(4)再用%1判斷是不是整數即可
最後執行時間32ms(faster than 93.76%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言