LeetCode 693 Binary Number with Alternating Bits 带有交替位的二进制数

来源:互联网 发布:已断开此网络登陆超时 编辑:程序博客网 时间:2024/06/05 20:56

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.

题目解析

对于给定的正整数,判断其是否有交替的二进制位,即:是否相邻的位有不同的值

解题思路

最简单的方法就是一位一位的进行判断,用变量bit记录上一个位置的值,初始值为-1,与1做与运算得到最低位的值,判断相邻两个值是否相同,相同返回false,循环退出后返回true。

/* C++ */class Solution {public:    bool hasAlternatingBits(int n) {        int bit = -1;        while (n > 0) {            if (n & 1 == 1) {                if (bit == 1) return false;                bit = 1;            } else {                if (bit == 0) return false;                bit = 0;            }            n >>= 1;        }        return true;    }};

另一种解法,利用0和1的交替特性,进行错位相加,组成全1的二进制数,然后再用一个检测全1的二进制数的trick,就是‘与’上加1后的数,因为全1的二进制数加1,就会进一位,并且除了最高位,其余位都是0,跟原数相‘与’就会得0,所以我们可以这样判断。比如n是10101,那么n>>1就是1010,二者相加就是11111,再加1就是100000,二者相‘与’就是0

/* C++ */class Solution {public:    bool hasAlternatingBits(int n) {        return ((n + (n >> 1) + 1) & (n + (n >> 1))) == 0;    }};
原创粉丝点击