给你两个二进制字符串,返回它们的和(用二进制表示)。

输入为 非空 字符串且只包含数字 1 和 0。

示例 1:

输入: a = “11”, b = “1” 输出: “100”

示例 2:

输入: a = “1010”, b = “1011” 输出: “10101”

题解

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func addBinary(a string, b string) string {

	res := ""
	carry := 0
	i, j := len(a)-1, len(b)-1
	for ; i >= 0 && j >= 0; i, j = i-1, j-1 {
		t := int(a[i]-'0') + int(b[j]-'0') + carry
		res = strconv.Itoa(t%2) + res
		carry = t / 2
	}

	for ; i >= 0; i = i - 1 {
		t := int(a[i]-'0') + carry
		res = strconv.Itoa(t%2) + res
		carry = t / 2
	}

	for ; j >= 0; j = j - 1 {
		t := int(b[j]-'0') + carry
		res = strconv.Itoa(t%2) + res
		carry = t / 2
	}

	if carry != 0 {
		res = "1" + res
	}
	return res
}