summary:
handle carry
package myapp.kit.leetcode.top200;
/**
*
* 67
* medium
* https://leetcode.com/problems/add-binary/
*
* Given two binary strings, return their sum (also a binary string).
*
* The input strings are both non-empty and contains only characters 1 or 0.
*
* Example 1:
*
* Input: a = "11", b = "1"
* Output: "100"
* Example 2:
*
* Input: a = "1010", b = "1011"
* Output: "10101"
*
*
* Constraints:
*
* Each string consists only of '0' or '1' characters.
* 1 <= a.length, b.length <= 10^4
* Each string is either "0" or doesn't contain any leading zero.
*
*Input
* "1010"
* "1011"
* Output
* "10010"
* Expected
* "10101"
* @author huangdingsheng
* @version 1.0, 2020/7/6
*/
public class add_binary_67 {
public static String addBinary(String a, String b) {
int m = a.length();
int n = b.length();
if (n == 0) {
return a;
}
if (m < n) {
return addBinary(b, a);
}
int[] result = new int[m + 1];
for (int i = 0; i < m - n; i++) {
b = "0" + b;
}
for (int i = 0; i < m; i++) {
result[i + 1] = (a.charAt(i) - '0') + (b.charAt(i) - '0');
}
StringBuilder sb = new StringBuilder();
for (int i = result.length - 1; i > 0; i--) {
sb.append(result[i] % 2);
result[i - 1] += result[i] / 2;
}
if (result[0] != '0') {
sb.append(result[0]);
}
String ans = sb.reverse().toString();
while (ans.length() > 1 && ans.charAt(0) == '0') {
ans = ans.substring(1);
}
return ans;
}
public static void main(String[] args) {
System.out.println(addBinary("1011", "1010"));
}
}