★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-yglfcgva-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.git
Example 1:github
Input: 5 Output: True Explanation: The binary representation of 5 is: 101
Example 2:微信
Input: 7 Output: False Explanation: The binary representation of 7 is: 111.
Example 3:spa
Input: 11 Output: False Explanation: The binary representation of 11 is: 1011.
Example 4:code
Input: 10 Output: True Explanation: The binary representation of 10 is: 1010.
給定一個正整數,檢查他是否爲交替位二進制數:換句話說,就是他的二進制數相鄰的兩個位數永不相等。htm
示例 1:blog
輸入: 5 輸出: True 解釋: 5的二進制數是: 101
示例 2:get
輸入: 7 輸出: False 解釋: 7的二進制數是: 111
示例 3:博客
輸入: 11 輸出: False 解釋: 11的二進制數是: 1011
示例 4:
輸入: 10 輸出: True 解釋: 10的二進制數是: 1010
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 return ((n + (n >> 1) + 1) & (n + (n >> 1))) == 0 4 } 5 }
4ms
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 4 var current = n % 2 5 var n = n / 2 6 while n > 0 { 7 if current == n % 2 { 8 return false 9 } 10 current = n % 2 11 n = n / 2 12 } 13 return true 14 } 15 }
12ms
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 let binaryString = String(n, radix: 2) 4 let count = binaryString.count 5 var i = 0 6 var flag = -1 7 while i < binaryString.count { 8 if flag != -1 { 9 guard flag != (n>>i) & 1 else { 10 return false 11 } 12 } 13 flag = (n>>i) & 1 14 i += 1 15 } 16 return true 17 } 18 }
12ms
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 let str = String(n,radix:2) 4 let characters = Array(str) 5 var result = true 6 for i in 0..<characters.count { 7 if i+1 < characters.count { 8 if characters[i] == characters[i+1] { 9 result = false 10 } 11 } 12 } 13 return result 14 } 15 }
24ms
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 var n = n 4 var bit0 = n & 1 5 n >>= 1 6 while n > 0 { 7 if n & 1 != bit0 { 8 bit0 = n & 1 9 n >>= 1 10 continue 11 } else { 12 return false 13 } 14 } 15 return true 16 } 17 }
28ms
1 class Solution { 2 func hasAlternatingBits(_ n: Int) -> Bool { 3 let str = toBinary(n) 4 for i in 0 ..< str.count - 1 { 5 let index1 = str.index(str.startIndex, offsetBy: i) 6 let index2 = str.index(str.startIndex, offsetBy: i + 1) 7 let c = str[index1 ..< index2] 8 let index3 = str.index(str.startIndex, offsetBy: i + 2) 9 let c1 = str[index2 ..< index3] 10 if String(c) == String(c1) { 11 return false 12 } 13 } 14 return true 15 } 16 17 func toBinary(_ n: Int) -> String { 18 var m = n 19 var str = "" 20 while m > 0 { 21 let temp = m % 2 22 str = "\(temp)" + str 23 m /= 2 24 } 25 return str 26 } 27 }