leetcode with python:342. Power of Four

题目:

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 mathclass 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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章