Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
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:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
Ideas of solving a problem
I couldn’t bring the best solution to the reader after spending nearly an hour. However, I found a very simple and clever way of thinking in other people’s problem solving. The following code extracts the last bit each time and continues the program if it is different from the previous bit. If it is the same as the previous bit, then print false directly. It is worth noting that the author first declared that t=2, which is a point that I did not think of, in the use of this point, the original author’s thinking is very clever. Through the complexity analysis, I can get the time and space complexity of this code. Its time complexity is O(n), and its space complexity is O(1). It consumes only 1.9 MB of memory. From a time and space-complexity perspective, this code is efficient and has a low memory footprint.
Code
package main
import (
"fmt"
)
func main(){
n :=5
fmt.Println(hasAlternatingBits(n))
}
func hasAlternatingBits(n int) bool {
t := 2
for n != 0 {
if t == n&1 {
return false
} else {
t = n&1
}
n >>= 1
}
return true
}
Output
True
链接:https://leetcode-cn.com/problems/binary-number-with-alternating-bits/solution/mei-ci-ti-qu-zui-hou-yi-wei-ji-lu-bi-jiao-by-hzlia/
来源:力扣(LeetCode)