Binary Number With Alternating Bits

I’m starting to get comfortable with bit manipulation and here’s another problem that I’ve solved in just a few amount of time.

class Solution {
    fun hasAlternatingBits(n: Int): Boolean {
        var temp = n
        var pos = temp and 1
        while(temp > 0){
            val m = temp and 1
            if(pos != m) return false
            
            temp = temp shr 1
            pos = pos xor 1
        }
        
        return true
    }
}  
Runtime: 0 ms, faster than 100.00% of Kotlin online submissions for Binary Number with Alternating Bits.
Memory Usage: 30.9 MB, less than 100.00% of Kotlin online submissions for Binary Number with Alternating Bits.

pos sets the expection. If it is 1, then it expects that the LSB is 1 or 0 otherwise. Again, we crawl bit by bit and flip the expected value. If the expected value and LSB does not match, then the number does not contain alternating bits.

comments powered by Disqus