Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"
b =
"1"
Return
"100"
.
/*
Maintain a variable to store the carry in each calculation.
time: O(n), space: O(1)
*/
public class Solution {
public String addBinary(String a, String b) {
if (a == null || a.length() == 0) {
return b;
}
if (b == null || b.length() == 0) {
return a;
}
int aIndex = a.length() - 1;
int bIndex = b.length() - 1;
int carry = 0;
String ans = "";
while (aIndex >= 0 || bIndex >= 0) {
int sum = carry;
if (aIndex >= 0) {
sum += a.charAt(aIndex) - '0';
}
if (bIndex >= 0) {
sum += b.charAt(bIndex) - '0';
}
carry = sum / 2;
ans = String.valueOf(sum % 2) + ans;
aIndex--;
bIndex--;
}
if (carry == 1) {
ans = "1" + ans;
}
return ans;
}
}
No comments:
Post a Comment