Binary Number with Alternating Bits

来源:互联网 发布:阮一峰javascript历史 编辑:程序博客网 时间:2024/06/05 09:44

Given a positive integer, check whether it has alternating bits or not.
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

//法一:class Solution {public:    bool hasAlternatingBits(int n)    {//5->101        int last = n & 1;//按位与取最后一个        n >>= 1;        while (n != 0)        {            if (last == (n & 1))//最后一个和次个比较            {                return false;            }            else            {                last = n & 1;            }            n >>= 1;        }        return true;    }};
//法二:class Solution {public:    bool hasAlternatingBits(int n)    {        int d = n & 1;        while ((n & 1) == d) //若d=1        {            d = 1 - d;//则d=0            n >>= 1;//右移,取次个,比较次个是否等于0        }        return n == 0;    }};