首页 > 其他分享 >leetcode 326. Power of Three

leetcode 326. Power of Three

时间:2023-05-30 17:34:16浏览次数:44  
标签:false Power int log10 isPowerOfThree 326 true leetcode Math

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?

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

 

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

 

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

 

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        """
        0 == false
        1 == true
        2 == false
        3 == true
        9 == true
        """
        return n in {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907,
               43046721, 129140163, 387420489, 1162261467}

 

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        """
        0 == false
        1 == true
        2 == false
        3 == true
        9 == true
        """
        Max3PowerInt = 1162261467 # 3^19, 3^20 = 3486784401 > MaxInt32
        MaxInt32 = 2147483647 # // 2^31 - 1    
        if (n <= 0 or n > Max3PowerInt): return False
        return Max3PowerInt % n == 0

 

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        """
        0 == false
        1 == true
        2 == false
        3 == true
        9 == true
        """
        if n <= 0: return False
        k = math.log(n, 3)
        return abs(k - round(k)) < 1e-10

 

 

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        """
        0 == false
        1 == true
        2 == false
        3 == true
        9 == true
        """
        Max3PowerInt = 1162261467 # 3^19, 3^20 = 3486784401 > MaxInt32
        MaxInt32 = 2147483647 # // 2^31 - 1    
        if (n <= 0 or n > Max3PowerInt): return False
        return Max3PowerInt % n == 0

 其他:

Method 1

Find the maximum integer that is a power of 3 and check if it is a multiple of the given input. (related post)

public boolean isPowerOfThree(int n) {
    int maxPowerOfThree = (int)Math.pow(3, (int)(Math.log(0x7fffffff) / Math.log(3)));
    return n>0 && maxPowerOfThree%n==0;
}

Or simply hard code it since we know maxPowerOfThree = 1162261467:

public boolean isPowerOfThree(int n) {
    return n > 0 && (1162261467 % n == 0);
}

It is worthwhile to mention that Method 1 works only when the base is prime. For example, we cannot use this algorithm to check if a number is a power of 4 or 6 or any other composite number.

Method 2

If log10(n) / log10(3) returns an int (more precisely, a double but has 0 after decimal point), then n is a power of 3. (original post). But be careful here, you cannot use log (natural log) here, because it will generate round off error for n=243. This is more like a coincidence. I mean when n=243, we have the following results:

log(243) = 5.493061443340548    log(3) = 1.0986122886681098
   ==> log(243)/log(3) = 4.999999999999999

log10(243) = 2.385606273598312    log10(3) = 0.47712125471966244
   ==> log10(243)/log10(3) = 5.0

This happens because log(3) is actually slightly larger than its true value due to round off, which makes the ratio smaller.

public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}

Method 3 related post

public boolean isPowerOfThree(int n) {
    return n==0 ? false : n==Math.pow(3, Math.round(Math.log(n) / Math.log(3)));
}

Method 4 related post

public boolean isPowerOfThree(int n) {
    return n>0 && Math.abs(Math.log10(n)/Math.log10(3)-Math.ceil(Math.log10(n)/Math.log10(3))) < Double.MIN_VALUE;
}

Cheating Method

This is not really a good idea in general. But for such kind of power questions, if we need to check many times, it might be a good idea to store the desired powers into an array first. (related post)

public boolean isPowerOfThree(int n) {
    int[] allPowerOfThree = new int[]{1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467};
    return Arrays.binarySearch(allPowerOfThree, n) >= 0;

标签:false,Power,int,log10,isPowerOfThree,326,true,leetcode,Math
From: https://blog.51cto.com/u_11908275/6381014

相关文章

  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • leetcode 27. Remove Element
    Givenanarraynumsandavalueval,removeallinstancesofthatvaluein-placeandreturnthenewlength.Donotallocateextraspaceforanotherarray,youmustdothisbymodifyingtheinputarrayin-placeTheorderofelementscanbechanged.Itdoesn&......
  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • leetcode 836. Rectangle Overlap
    Arectangleis representedasa list[x1,y1,x2,y2],where (x1,y1) arethecoordinatesofitsbottom-leftcorner,and(x2, y2) arethecoordinatesofitstop-rightcorner.Tworectanglesoverlapiftheareaoftheirintersectionispositive. Tobecl......
  • leetcode 342. Power of Four
    Givenaninteger(signed32bits),writeafunctiontocheckwhetheritisapowerof4.Example:Givennum=16,returntrue.Givennum=5,returnfalse.Followup:Couldyousolveitwithoutloops/recursion?解法1,经典的数学解法:classSolution(object):def......
  • leetcode 345. Reverse Vowels of a String
    Writeafunctionthattakesastringasinputandreverseonlythevowelsofastring.Example1:Givens="hello",return"holle".Example2:Givens="leetcode",return"leotcede".Note:Thevowelsdoesnotincl......
  • leetcode Most Common Word——就是在考察自己实现split
    819.MostCommonWordGivenaparagraph andalistofbannedwords,returnthemostfrequentwordthatisnotinthelistofbannedwords. Itisguaranteedthereisatleastonewordthatisn'tbanned,andthattheanswerisunique.Wordsinthelist......
  • leetcode Kth Largest Element in a Stream——要熟悉heapq使用
    703.KthLargestElementinaStreamEasyDesignaclasstofind thekthlargestelementinastream.Notethatitisthekthlargestelementinthesortedorder,notthekthdistinctelement.Your KthLargest classwillhaveaconstructorwhichacceptsanin......
  • leetcode 2712. 使所有字符相等的最小成本
    2712.使所有字符相等的最小成本给你一个下标从 0 开始、长度为 n 的二进制字符串 s ,你可以对其执行两种操作:选中一个下标 i 并且反转从下标 0 到下标 i(包括下标 0 和下标 i )的所有字符,成本为 i+1 。选中一个下标 i 并且反转从下标 i 到下标 n-......
  • leetcode 2707. 字符串中的额外字符
    2707.字符串中的额外字符给你一个下标从 0 开始的字符串 s 和一个单词字典 dictionary 。你需要将 s 分割成若干个 互不重叠 的子字符串,每个子字符串都在 dictionary 中出现过。s 中可能会有一些 额外的字符 不在任何子字符串中。请你采取最优策略分割 s......