[Swift]LeetCode326. 3的幂 | Power of Three
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公眾號:山青詠芝(shanqingyongzhi)
?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/9757245.html?
?如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
?原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27 Output: trueExample 2:
Input: 0 Output: falseExample 3:
Input: 9 Output: trueExample 4:
Input: 45 Output: falseFollow up:
Could you do it without using any loop / recursion?
給定一個整數,寫一個函數來判斷它是否是 3?的冪次方。
示例 1:
輸入: 27 輸出: true示例 2:
輸入: 0 輸出: false示例 3:
輸入: 9 輸出: true示例 4:
輸入: 45 輸出: false進階:
你能不使用循環或者遞歸來完成本題嗎?
?
232ms
1 class Solution { 2 func isPowerOfThree(_ n: Int) -> Bool { 3 //遞歸 4 if n <= 0 {return false} 5 if n == 1 {return true} 6 return (n % 3 == 0) && isPowerOfThree(n / 3) 7 } 8 }224ms
1 class Solution { 2 func isPowerOfThree(_ n: Int) -> Bool { 3 var threeInPower = 1 4 while threeInPower <= n { 5 6 if threeInPower == n { 7 return true 8 } 9 10 threeInPower *= 3 11 } 12 return false 13 } 14 }228ms
1 class Solution { 2 func isPowerOfThree(_ n: Int) -> Bool { 3 return n > 0 && 1162261467 % n == 0 4 } 5 }256ms
1 class Solution { 2 func isPowerOfThree(_ num: Int) -> Bool { 3 return num > 0 && (Int(pow(Double(3),Double(19))) % num == 0); 4 } 5 }?
轉載于:https://www.cnblogs.com/strengthen/p/9757245.html
總結
以上是生活随笔為你收集整理的[Swift]LeetCode326. 3的幂 | Power of Three的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php system()和exec()差
- 下一篇: 第13次预习课-20180919 多进程