Simple Java Solution


  • 0

    Numbers with alternating bits are 1,2,5,10,21,42,85 etc.
    This follows a kind of series where in every next number is double of the previous with alternate addition of 1.

    class Solution {
        public boolean hasAlternatingBits(int n) {
            int i = 2;
            boolean add_1 = true;
            
            while(i <= n && i > 0){
                if(i == n ) return true;
                i = i * 2 + (add_1 ? 1 : 0);            
                add_1 = !add_1;
            }
                
            return n == 1;
        }
    }
    

Log in to reply
 

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