https://leetcode-cn.com/problems/binary-number-with-alternating-bits/
Given a positive integer, to check whether he is an alternating-bit binary numbers: in other words, is his two-digit binary number adjacent never equal.
Example 1:
Input: 5
Output: True
Explanation:
binary number is 5: 101
Example 2:
Input: 7
Output: False
Explanation:
binary number is 7: 111
Example 3:
Input: 11
Output: False
Explanation:
binary number is 11: 1011
Example 4:
Input: 10
Output: True
Explanation:
binary number is 10: 1010
Chicken dishes to try:
Violence method does not go into details, a slight modification of the violent way the code on the line, not posted here
Worship Gangster Code:
1 class Solution { 2 public: 3 bool hasAlternatingBits(int n) { 4 n = (n ^ (n>>1)); 5 return (n & ((long)n+1)) == 0; 6 } 7 };
The number of right one (bit operation), and the original number of XOR
1010101 1110101
1010101 1110101
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/binary-number-with-alternating-bits
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.