[LeetCode] 326. Power of Three 3的次方数
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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
给一个整数,写一个函数来判断此数是不是3的次方数。
类似的题目Power of Two 中,由于2的次方数的特点,用位操作很容易。而3的次方数没有显著的特点,最直接的方法就是不停地除以3,最后判断是否能整除。
follow up是否不用任何循环或递归。
解法1: 循环
解法2: 迭代
解法3:取对数
Java:
1 2 3 4 5 | class Solution { public boolean isPowerOfThree( int n) { return n > 0 && Math.pow( 3 , Math.round(Math.log(n) / Math.log( 3 ))) == n; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 | class Solution( object ): def isPowerOfThree( self , n): """ :type n: int :rtype: bool """ if n < = 0 : return False while n ! = 1 : if n % 3 ! = 0 : return False n / = 3 return True |
Python:
1 2 3 4 5 6 7 8 9 | class Solution( object ): def isPowerOfThree( self , n): """ :type n: int :rtype: bool """ if n < = 0 : return False if n = = 1 : return True return n % 3 = = 0 and self .isPowerOfThree(n / 3 ) |
Python:
1 2 3 4 5 6 7 | class Solution( object ): def isPowerOfThree( self , n): """ :type n: int :rtype: bool """ return n > 0 and 3 * * round (math.log(n, 3 )) = = n |
Python:
1 2 3 | class Solution( object ): def isPowerOfThree( self , n): return n > 0 and (math.log10(n) / math.log10( 3 )).is_integer() |
Python:
1 2 3 4 5 6 7 8 9 10 11 | class Solution( object ): def __init__( self ): self .__max_log3 = int (math.log( 0x7fffffff ) / math.log( 3 )) self .__max_pow3 = 3 * * self .__max_log3 def isPowerOfThree( self , n): """ :type n: int :rtype: bool """ return n > 0 and self .__max_pow3 % n = = 0 |
C++:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : bool isPowerOfThree( int n) { if (n <= 0) return false ; while (n > 1){ if (n %3 != 0) return false ; n/=3; } return true ; } }; |
C++:
1 2 3 4 5 6 7 8 | class Solution { public : bool isPowerOfThree( int n) { if (n <= 0) return false ; if (n == 1) return true ; return n % 3 == 0 && isPowerOfThree(n / 3); } }; |
C++:
1 2 3 4 5 6 | class Solution { public : bool isPowerOfThree( int n) { return n > 0 && pow (3, round( log (n) / log (3))) == n; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步