Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
public class Solution {
public String addBinary(String a, String b) {
int lenA = a.length();
int lenB = b.length();
int carry = 0;
String res = "";
int len = Math.max(lenA, lenB);
for (int i = 0; i < len; i++) {
int m;
int n;
if (i < lenA) {
m = a.charAt(lenA-i-1) - '0';
} else {
m = 0;
}
if (i < lenB) {
n = b.charAt(lenB-i-1) - '0';
} else {
n = 0;
}
int temp = m+n+carry;
carry = temp/2;
res = temp % 2 + res;;
}
return (carry==0) ? res : carry+res;
}
}
368

被折叠的 条评论
为什么被折叠?



