Problem
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:
1 |
|
Example 2:
1 |
|
Explanation
-
Similar to 2. Add Two Numbers. First, we need to create a stringbuilder
res
to hold the result. We need a pointer pointing at the end index of stringA, and another pointer pointing at the end index of stringB because we add these two numbers starting from the least significant digit. -
While either of the pointer is not negative, We can create a
sum
to hold the sum of two digit each time we add, and initialize the this sum equal tocarry
, wherecarry
initialize to 0 before we start calculating. -
After adding two digits to the sum, now the result digit’s value will be
sum % 2
and we added it to the stringbuilder, and carry will besum / 2
. Repeat this while loop. -
Outside of the while loop, if the
carry
is not zero, then we append it to theres
, and we reverse theres
and return its string representation.
Solution
1 |
|