Binary Number with Alternating Bits

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

直接照字面方法解,先轉成二進位字串,再逐一比對是否相異

class Solution {
    public boolean hasAlternatingBits(int n) {
        char[] binaryCh = Integer.toBinaryString(n).toCharArray();
        
        for(int i=0; i<binaryCh.length-1; i++) {
            if(binaryCh[i] == binaryCh[i+1]) return false;
        }
        
        return true;
    }
}

 

高手解法

https://discuss.leetcode.com/topic/106356/oneliners-c-java-ruby-python/2