Add Binary Leetcode


#1

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

#2

Start from the end of both the given binary strings, do a -'0' at each character to get it’s int value, add it to the sum. add sum%2 value to the result and assign sum/2 to carry. At the start of the loop, assign carry to sum.

func addBinary(a string, b string) string {
    al := len(a)-1
    bl := len(b)-1
    
    sum, carry := 0, 0
    var result strings.Builder
    for al>=0 || bl >=0{
        sum = carry
        if al>=0{
            sum += int(a[al]-'0')
            al--
        }
        if bl>=0{
            sum += int(b[bl]-'0')
            bl--
        }
        result.WriteString(strconv.Itoa(sum%2))
        carry = sum/2
    }
    if carry!=0{
         result.WriteString(strconv.Itoa(carry))
    }
    
    resultRunes := []rune(result.String())
    return reverse(resultRunes)
}

func reverse(result []rune) string {
    j := len(result)-1
    for i:=0; i<j; i++ {
        result[i], result[j] = result[j], result[i]
        j--
    }
    return string(result)
}