Fast and Concise Java Solution(Beats 100% solutions)


  • 0
    K
    class Solution {
        public boolean hasAlternatingBits(int n) {
            int last=n%2,cur;
            n=n/2;
            while(n>0){
                cur=n%2;
                if(cur==last) return false;
                last=cur;
                n=n/2;
            }
            return true;
        }
    }
    

  • 0

    Same idea as yours, using the bit manipulation though:

    public boolean hasAlternatingBits(int n) {
            int diff = n & 1;
            n = n >> 1;
            while (n != 0) {
                int temp = n & 1;
                if (diff == temp) return false;
                diff = temp;
                n = n >> 1;
            }
            return true;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.