给定两个二进制字符串,返回它们的和(也是一个二进制字符串)
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) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {//从后往前加,因为后面是低位,前面是高位
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';//(j--)返回j,再做--操作
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}
我的解法
class Solution {
public String addBinary(String a, String b) {
if (a.isEmpty())
return b;
if (b.isEmpty())
return a;
int carry = 0;
int addA = 0;
int addB = 0;
StringBuilder aB = new StringBuilder(a);
StringBuilder bB = new StringBuilder(b);
aB.reverse();
bB.reverse();
StringBuilder sum = new StringBuilder();
for (int i = 0; i < Math.max(a.length(), b.length()); i++) {
if (i >= a.length())
addA = 0;
else
addA = aB.charAt(i) - '0';
if (i >= b.length())
addB = 0;
else
addB = bB.charAt(i) - '0';
sum.insert(0, (addA + addB + carry) % 2);
if (addA + addB + carry >= 2)
carry = 1;
else
carry = 0;
}
if (carry == 1)
sum.insert(0, 1);
return sum.toString();
}
}