LWC 53:693. Binary Number with Alternating Bits

2018-01-02 10:58:08 浏览数 (1)

LWC 53:693. Binary Number with Alternating Bits

传送门:693. Binary Number with Alternating Bits

Problem:

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.

思路: 熟悉JAVA接口的知道,Integer类可以直接把数字转为2进制串。

代码如下:

代码语言:javascript复制
    public boolean hasAlternatingBits(int n) {
        String binary = Integer.toBinaryString(n);
        char[] cs = binary.toCharArray();
        int bit = cs[0] - '0';
        for (int i = 1; i < cs.length;   i) {
            if (bit == cs[i] - '0') return false;
            bit = cs[i] - '0';
        }
        return true;
    }

当然,你也可以自己解析每一位,代码如下:

代码语言:javascript复制
    public boolean hasAlternatingBits(int n) {
        int bit = n >> 0 & 1;
        n >>= 1;
        while (n > 0) {
            if (bit == (n & 1)) return false;
            bit = n & 1;
            n >>= 1;
        }
        return true;
    }

或者合并到一块:

代码语言:javascript复制
    public boolean hasAlternatingBits(int n) {
        int bit = -1;
        while (n > 0) {
            if (bit == (n & 1)) return false;
            bit = n & 1;
            n >>= 1;
        }
        return true;
    }    

0 人点赞