leetcode with python:326. Power of Three

题目:

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

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

给定一数,判断它是否是3的次方

这题除了底数换成3,跟231.根本一模一样

class Solution:    def isPowerOfThree(self, n: int) -> bool:        if n<=0: #0和负数不在讨论範围            return False                while n%3==0:            n=n//3        return n==1

将一数不断除三直到不能整除
看最后结果是不是1,就知道该数是不是3的次方了
最后执行时间77ms(faster than 96.06%)

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

import mathclass Solution:    def isPowerOfThree(self, n: int) -> bool:        if n<=0: #0和负数不在讨论範围            return False        return (math.log10(n)/math.log10(3))%1==0

透过log的性质,我们可以知道log3(3的次方数)会是整数
且log10(n)/log10(3)=log3(n)
所以我们只要计算log10(n)/log10(3)再用%1判断是不是整数即可
最后执行时间60ms(faster than 99.86%)

那我们下题见


关于作者: 网站小编

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

热门文章