题目
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
本想图省事,直接用java类库里提供的parseLong函数,结果测试用例里面会给出很长的字符串。
那就只能按规矩写了。
代码
public class AddBinary {
public static final int RADIX = 2;
public String addBinary(String a, String b) {
int shorterLen = a.length();
int longerLen = b.length();
char[] shorterArray = a.toCharArray();
char[] longerArray = b.toCharArray();
if (a.length() > b.length()) {
shorterLen = b.length();
longerLen = a.length();
// swap
char[] temp = shorterArray;
shorterArray = longerArray;
longerArray = temp;
}
int carry = 0;
for (int i = 0; i < shorterLen; ++i) {
int result = (shorterArray[shorterLen - 1 - i] - ‘0‘)
+ (longerArray[longerLen - 1 - i] - ‘0‘) + carry;
carry = result / RADIX;
longerArray[longerLen - 1 - i] = (char) (result % RADIX + ‘0‘);
}
for (int i = longerLen - shorterLen - 1; i >= 0; --i) {
int result = (longerArray[i] - ‘0‘) + carry;
carry = result / RADIX;
longerArray[i] = (char) (result % RADIX + ‘0‘);
}
String result = new String(longerArray);
if (carry == 1) {
result = 1 + result;
}
return result;
}
}LeetCode | Add Binary,布布扣,bubuko.com
原文:http://blog.csdn.net/perfect8886/article/details/21275951