693.binary number with alternating bits

Bit Manipulation, Easy

Question

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

1
2
3
4
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

1
2
3
4
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

1
2
3
4
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

1
2
3
4
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.

My Answer

1
2
3
4
5
class {
public boolean hasAlternatingBits(int n) {
return (((long)n + (n>>1) + 1) & ((long)n + (n>>1))) == 0;
}
}

Running time: O(n), n is the length bit of the given number, 15ms