Java bitwise AND solution


  • 0
    P

    My solution -

    class Solution {
        public boolean hasAlternatingBits(int n) {
            boolean next_expect_1 = (n & 1) == 1;
            boolean next_expect_0 = (n & 0) == 0;
            boolean maintain = false;
            
            
            while (n > 0) {
                if (((n & 1) == 1) && next_expect_1) {
                    next_expect_1 = false;
                    next_expect_0 = true;
                    maintain = true;                
                } else if (((n & 1) == 0) && next_expect_0){
                    next_expect_1 = true;
                    next_expect_0 = false;
                    maintain = true;                
                } else {                
                    return false;
                }            
                n = n >> 1;                        
            }
            
            return maintain;
        }
    }````

Log in to reply
 

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