[Swift]LeetCode326. 3的冪 | Power of Three

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-qqliyaap-kc.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an integer, write a function to determine if it is a power of three.git

Example 1:github

Input: 27
Output: true

Example 2:微信

Input: 0
Output: false

Example 3:函數

Input: 9
Output: true

Example 4:oop

Input: 45
Output: false

Follow up:
Could you do it without using any loop / recursion?spa


給定一個整數,寫一個函數來判斷它是不是 3 的冪次方。code

示例 1:htm

輸入: 27
輸出: true

示例 2:blog

輸入: 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 }
相關文章
相關標籤/搜索