Add Binary
1 min read

Add Binary

Given two binary strings (strings containing only 1s and 0s) return their sum (also as a binary string).
Note: neither binary string will contain leading 0s unless the string itself is 0

Ex: Given the following binary strings...

"100" + "1", return "101"
"11" + "1", return "100"
"1" + "0", return  "1"
fun addBinary(binaryOne: String, binaryTwo: String): String {
    val sb = StringBuilder()
    var i = binaryOne.length -1
    var j = binaryTwo.length -1
    var carry = 0
    
    while(i >= 0 || j >= 0) {
        var sum = carry
        if(i >= 0) {
            sum += binaryOne[i--] - '0'
        }
        
        if(j >=0) {
            sum += binaryTwo[j--] - '0'
        }
        
        sb.insert(0,sum.mod(2))
        carry = sum.div(2)
    }
    
    if(carry > 0){
        sb.insert(0,1)
    }
    return sb.toString()
}

Enjoying these posts? Subscribe for more