--- title: 'LeetCode 693. Binary Number with Alternating Bits' disqus: hackmd --- # LeetCode 693. Binary Number with Alternating Bits ## Description Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. ## Example Input: n = 5 Output: true Explanation: The binary representation of 5 is: 101 Input: n = 7 Output: false Explanation: The binary representation of 7 is: 111. ## Constraints 1 <= n <= 2^31^ - 1 ## Answer 此題可藉由0xaaaaaaaa跟0x55555555都是交錯的二進位來處理,所以交錯數對n做&仍為原數。而n|n>>2是用來防範2的次方數,2的次方取n|n>>2就會變交錯數,如此對交錯數做&就不會是原數了。 ```Cin= //2022_03_13 bool hasAlternatingBits(int n){ return (( (n|n>>2) & 0x55555555 ) == n) || (( (n|n>>2) & 0xaaaaaaaa ) == n); } ``` ## Link https://leetcode.com/problems/binary-number-with-alternating-bits/ ###### tags: `Leetcode`