# 693. Binary Number with Alternating Bits 交替位二进制数

@TOC

## # 题目描述

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.
``````

## # 解题方法

### # 方法一：遍历判断

``````In [1]: bin(5)
Out[1]: '0b101'
``````

``````class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bin_n = bin(n)[2:]
return all(int(bin_n[i]) + int(bin_n[i+1]) == 1 for i in xrange(len(bin_n) - 1))
``````

``````class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bin_n = bin(n)[2:]
return all(bin_n[i] != bin_n[i+1] for i in xrange(len(bin_n) - 1))
``````

### # 方法二：判断是否是交替模式

``````class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
b = 0b1010101010101010101010101010101010101010101010101010101010101010
while b > 0:
if b == n:
return True
b = b >> 1
return False
``````

### # 方法三：位运算

``````In [1]: n = 5

In [2]: bin(n)
Out[2]: '0b101'

In [3]: bin(n >> 1)
Out[3]: '0b10'

In [4]: bin(n ^ (n >> 1))
Out[4]: '0b111'
``````

``````In [1]: n = 5

In [2]: bin(n)
Out[2]: '0b111'

In [3]: bin(n + 1)
Out[3]: '0b1000'

In [4]: n & n + 1
Out[4]: 0

In [5]: not (n & n + 1)
Out[5]: True
``````

``````class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
n ^= (n >> 1)
return not (n & n + 1)
``````

## # 总结

1. 熟练掌握位运算技巧，才不会迷茫哦！
2. 你学到了吗？留个言吧！

## # 日期

2018 年 1 月 17 日 2018 年 11 月 ９ 日 —— 睡眠可以 2022 年 3 月 28 日 —— 早起时间利用很可以，公众号转载+题解一篇