★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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: true
Example 2:
Input: 0 Output: false
Example 3:
Input: 9 Output: true
Example 4:
Input: 45 Output: false
Follow 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 }