题目

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.

题目地址

讲解

这一题的意思是判断一个整数的二进制形式,是否是0和1互相间隔排列的。题目挺简单的,但我想做的是空间O(1)。所以我用两个变量来存储遍历过程中需要保存的前一位和后一位,然后设置一个首次访问flag。遍历一遍二进制,结果就出来了。

java代码

class Solution {
    public boolean hasAlternatingBits(int n) {
        if(n<=2){
            return true;
        }
        int temp = n;
        int now = 0;
        int previous = 0;
        boolean flag = true;
        while(temp>0){
            if(flag){
                now = temp%2;
                temp >>= 1;
                flag = false;
            }else{
                previous = now;
                now = temp%2;
                if(previous==now){
                    return false;
                }
                temp >>= 1;
            }
        }
        return true;
    }
}

liuqinh2s
42 声望13 粉丝

认真写代码,搞创作