LeetCode 693. Binary Number with Alternating Bits

来源:互联网 发布:linux 桌面虚拟化 编辑:程序博客网 时间:2024/05/24 04:17
693. 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.


代码实现如下:

思路1:
用 t 表示该数字的最后一位,比如10的二进制为1010,则 t = 0;
n /= 2; 如果其二进制最后一位 t 总是等于 n / 2 后剩下的最后一位,说明其二进制相邻位置有相同值,即不交互,返回false;
否则返回true;

class Solution {
    public boolean hasAlternatingBits(int n) {
        int t = n % 2;
        n /= 2;
        while(n > 0){
            if(t == n % 2) return false;
            t = n % 2;
            n /= 2;
        }
        return true;
    }
}

思路2:
调用Integer.toBinaryString()方法将十进制数转换位二进制字符串,依次比较当前位是否与下一位相等,相等返回false,否则返回true
class Solution {
    public boolean hasAlternatingBits(int n) {
        String bits = Integer.toBinaryString(n);
        for(int i = 0; i < bits.length() - 1; i++){
            if(bits.charAt(i) == bits.charAt(i + 1)) return false;
        }
        return true;
    }
}