Java for LeetCode 067 Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

解题思路:

JAVA实现如下:

static public String addBinary(String a, String b) {
if (a.length() < b.length()) {
String temp = a;
a = b;
b = temp;
}
boolean carry = false;
StringBuilder sb = new StringBuilder(a);
for (int i = 0; i < b.length(); i++) {
if (b.charAt(b.length() - 1 - i) == '0') {
if (sb.charAt(a.length() - 1 - i) == '0' && carry) {
sb.replace(a.length() - 1 - i, a.length() - i, "1");
carry = false;
} else if (sb.charAt(a.length() - 1 - i) == '1' && carry)
sb.replace(a.length() - 1 - i, a.length() - i, "0");
} else {
if (sb.charAt(a.length() - 1 - i) == '0' && !carry)
sb.replace(a.length() - 1 - i, a.length() - i, "1");
else if (sb.charAt(a.length() - 1 - i) == '1' && !carry) {
sb.replace(a.length() - 1 - i, a.length() - i, "0");
carry = true;
}
}
}
if (!carry)
return sb.toString();
for (int i = a.length() - b.length() - 1; i >= 0; i--)
if (sb.charAt(i) == '0') {
sb.replace(i, i + 1, "1");
return sb.toString();
} else
sb.replace(i, i + 1, "0");
sb.insert(0, '1');
return sb.toString();
}
上一篇:2017杭州·云栖大会第二天:阿里云发布了这些“黑科技”


下一篇:去除input在谷歌下的focus效果