[LeetCode] Binary Number with Alternating Bits

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.

判断一个数字的二进制是否是01交替出现的。直接循环按位与1即可,如果是交替出现,则每次结果都不同,如果出现相同的结果,返回false即可。

class Solution {
public:
    bool hasAlternatingBits(int n) {
        int a = 0, b = 0, bit = 1;
        while (n) {
            a = n & bit;
            n >>= 1;
            b = n & bit;
            if (a == b)
                return false;
        }
        return true;
    }
};
// 6 ms

 

posted @ 2017-10-09 21:41  immjc  阅读(152)  评论(0编辑  收藏  举报