★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vyhqcjqi-mc.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an integer, write a function to determine if it is a power of two.git
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.github
給定一個整數,編寫一個函數來判斷它是不是 2 的冪次方。微信
示例 1:函數
輸入: 1 輸出: true 解釋: 20 = 1
示例 2:this
輸入: 16 輸出: true 解釋: 24 = 16
示例 3:spa
輸入: 218 輸出: false
12ms
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 for i in 0..<32 { 4 if n == 1 << i { 5 return true 6 } 7 } 8 9 return false 10 } 11 }
12mscode
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 if n <= 0 { return false } 4 if n == 1 { return true } 5 var current = n 6 while current > 2 { 7 if current % 2 != 0 { 8 return false 9 } else { 10 current = current / 2 11 } 12 } 13 return true 14 } 15 }
16mshtm
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 guard n > 0 else { return false } 4 return String(n, radix: 2).filter { $0 == "1" }.count == 1 5 } 6 }
20msblog
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 if (n <= 0) { 4 return false 5 } 6 var rencontre = false 7 for digit in String(n, radix: 2) { 8 if (digit == "1") { 9 if rencontre { 10 return false 11 } else { 12 rencontre = true 13 } 14 } 15 } 16 17 return true 18 } 19 }
20ms
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 4 guard n > 0 else { 5 return false 6 } 7 8 var num = n 9 10 while num != 0 { 11 12 if num == 1 || num == 2 { 13 return true 14 } 15 16 if num % 2 != 0 { 17 return false 18 } 19 20 num /= 2 21 } 22 23 return true 24 25 } 26 }
24ms
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 if (n == 0) { 4 return false; 5 } 6 return n & (n-1) == 0 7 } 8 }
32ms
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 var number:Int = n; 4 if number != 0 && number > 0 { 5 if number == 1 || number == 2{ 6 return true; 7 } 8 while (number%2 == 0) { 9 if (number == 2) { 10 break; 11 } 12 number = number / 2; 13 } 14 if (number % 2 == 0) { 15 return true; 16 } 17 } 18 return false; 19 } 20 }
48ms
1 class Solution { 2 func isPowerOfTwo(_ n: Int) -> Bool { 3 if n <= 0 { 4 return false 5 } 6 return 1<<32 % n == 0 7 } 8 }