Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
and 0
.
'0'
or '1'
characters.1 <= a.length, b.length <= 10^4
."0"
.First, you need to unify the lengths of the two strings. Determine the length of the two strings, then select the shorter string and pad it with '0'
in front of the string, that is, use the String.prototype.padStart()
method to pad it. Then define the target string and the carry flag variable. Then iterate through the strings from the end to the beginning, convert the characters in the strings to numbers, add them together, and add them to the carry variable. The ~~
is used to convert characters to numbers using bit manipulation. After the addition is complete, set the carry flag to 0
, then determine if the character is greater than 2
. If it is greater than or equal to 2
, subtract 2
from the added character and set the carry flag to 1
. If it is less than 2
, simply concatenate the string, and then continually loop to complete the concatenation of the target string. If there is still a carry flag at the end, simply concatenate1
to the front of the target string and then return it.