Title:Add Binary 67
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/add-binary/
1. 用0补齐最短字符串左侧,至两字符串等长
时间复杂度:O(n),一次一层for循环。
空间复杂度:O(1),申请StringBuilder,最长为n。
/**
* 用0补齐最短字符串左侧,至两字符串等长
* StringBuilder insert()
* @param a
* @param b
* @return
*/
public static String addBinary(String a, String b) {
int aLen = a.length();
int bLen = b.length();
int maxLen = Math.max(aLen, bLen);
int add = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxLen; i++) {
int aTmp = i < aLen ? a.charAt(i) - '0' : 0;
int bTmp = i < bLen ? b.charAt(i) - '0' : 0;
sb.insert(0,(aTmp + bTmp + add) % 2);
add = (aTmp + bTmp + add) > 1 ? 1 : 0;
}
if (add == 1) {
sb.insert(0, 1);
}
return sb.toString();
}