Java 1-line


  • 0
    2
    class Solution {
        public boolean hasAlternatingBits(int n) {
            return Integer.toBinaryString(n).matches("(10)*1{0,1}");
        }
    }
    

  • 0

    @2499370956 thanks for sharing! Inspired by your solution, here is 1-line C++ using bitset and regex...

    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            return regex_match(bitset<32>(n).to_string(),regex("(0)*(10)*1{0,1}"));
        }
    };
    

Log in to reply
 

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