Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
自己的解答:
public String addBinary(String a, String b) {
if (a == null || b == null)
return null;
int base = 2;
int max = a.length() > b.length() ? a.length() : b.length();
char[] result = new char[max+1];
int sum, carry = 0, i, j, k;
for (i = a.length()-1, j = b.length()-1, k = result.length-1; i >= 0 && j >= 0; i--,j--) {
sum = a.charAt(i) + b.charAt(j) + carry- 2*'0';
carry = sum/base;
result[k--] = (char) (sum%base + '0');
}
while (i >= 0) {
sum = a.charAt(i) + carry- '0';
carry = sum/base;
result[k--] = (char) (sum%base + '0');
i--;
}
while (j >= 0) {
sum = b.charAt(j) + carry- '0';
carry = sum/base;
result[k--] = (char) (sum%base + '0');
j--;
}
if (carry == 1) {
result[0] = '1';
return String.copyValueOf(result, 0, result.length);
}
return String.copyValueOf(result, 1, result.length-1);
}
最通用的方法,或者说,以上代码改成八进制,十进制,十六进制都是可以用的,只需要修改base的值即可。也比较适合于大数相加。贴一下别人的代码,大同小异:
public String addBinary(String a, String b) {
if(a == null || a.isEmpty()) {
return b;
}
if(b == null || b.isEmpty()) {
return a;
}
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
StringBuilder stb = new StringBuilder();
int i = aArray.length - 1;
int j = bArray.length - 1;
int aByte;
int bByte;
int carry = 0;
int result;
while(i > -1 || j > -1 || carry == 1) {
aByte = (i > -1) ? Character.getNumericValue(aArray[i--]) : 0;
bByte = (j > -1) ? Character.getNumericValue(bArray[j--]) : 0;
result = aByte ^ bByte ^ carry;
carry = ((aByte + bByte + carry) >= 2) ? 1 : 0;
stb.append(result);
}
return stb.reverse().toString();
}