Add Binary

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

The input strings are both non-empty and contains only characters1or 0.

Example 1:

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

Output:
 "100"

Example 2:

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

Output:
 "10101"

Analysis

Easy难度,但是有一些需要注意的点:

在计算过程不可以将a,b都转化为数(Integer/Long)来求和,因为测试样例和题中并没有限制数据的长度大小,因此会溢出导致错误。

返回String字符串,动态字符串可以用StringBuilder(或者StringBuffer,如果用多线程,因为StringBuffer是sync),减小字符串拼接时间复杂度 (O(n^2) - > O(n))

从低位到高位的顺序进行相加求和,因此得到的StringBuilder是逆序,需要翻转后输出。

Solution

Preferred Implementation - Binary Conversion

Computation from string usually can be simplified by using a carry as such.

Using Bit operation XOR

错误方法会在数据较大时溢出从而导致错误:

Wrong Answer:

207 / 294 test cases passed.

Wrong Way:

Last updated

Was this helpful?