Binary Gap

This is a bit manipulation problem and the solution, although a bit verbose is really efficient beating 100% of all submission for Kotlin.

class Solution {
    fun binaryGap(N: Int): Int {
        if(Integer.bitCount(N) <= 1) return 0
        
        // remove all zero LSB
        var temp = N
        while(true){
            if(temp and 1 != 0) break
            temp = temp shr 1
        }
        
        var ctr = 0
        var max = Integer.MIN_VALUE
        
        while(temp > 0){
            temp = temp shr 1
            ctr++
            if(temp and 1 == 1) {
                max = Math.max(max, ctr)
                ctr = 0
            }
        }
        
        return max
    }
}
Runtime: 128 ms, faster than 100.00% of Kotlin online submissions for Binary Gap.
Memory Usage: 31 MB, less than 100.00% of Kotlin online submissions for Binary Gap.
comments powered by Disqus