[Java/C++] Clean Code


  • 0

    Java

    class Solution {
        public boolean hasAlternatingBits(int n) {
            for (int prev = 1 - (n % 2); n > 0; prev = n % 2, n /= 2)
                if (n % 2 == prev) return false;
    
            return true;
        }
    }
    

    C++

    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            for (int prev = !(n % 2); n; prev = n % 2, n /= 2)
                if (n % 2 == prev) return false;
    
            return true;
        }
    };
    

Log in to reply
 

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