Leetcode 326. Power of Three

Problem

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^x 3x.

Algorithm

The maximum power of 3 within the range of an integer is 3 19 = 1162261467 3^{19} = 1162261467 319=1162261467. Therefore, to determine whether n is a power of 3, it is sufficient to check whether 1162261467 mod n = 0.

Code

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        
        return 1162261467 % n == 0

你可能感兴趣的:(入门题,解题报告,leetcode,算法,职场和发展)