67. Add Binary
題目連結
難易度:Easy
Given two binary strings a and b, return their sum as a binary string.
Example 1:1
2Input: a = "11", b = "1"
Output: "100"
Example 2:1
2Input: a = "1010", b = "1011"
Output: "10101"
Example 3:1
2Input: digits = [0]
Output: [1]
Constraints:
1 <= a.length, b.length <= 104
a
andb
consist only of'0'
or'1'
characters.- Each string does not contain leading zeros except for the zero itself.
Concept
The length of string a and b might not be the same, so find the max length of them first.
Loop the string a and b from the end, calculate the sum of current a+b+carry, and remember to convert it to the Number before adding them up.
If it exceeds the string length, then the current a or b number will be zero. The current position value in the result array can be calculated by sum % 2, and the carry can be calculated by Math.floor(sum / 2)
After the for loop, if there is a carry value, unshift it to the array
Solution
1 | /** |