Question:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class Solution { public String addBinary(String a, String b) { StringBuffer sb = new StringBuffer(); String s1 = sb.append(a).reverse().toString(); sb.delete(0, sb.length()); String s2 = sb.append(b).reverse().toString(); sb.delete(0, sb.length()); char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); int c1number = 0; int c2number = 0; int carry = 0; int n = Math.max(c1.length, c2.length); for (int i = 0; i < n; i++) { if (i < c1.length) { c1number = c1[i] - ‘0‘; } else { c1number = 0; } if (i < c2.length) { c2number = c2[i] - ‘0‘; } else { c2number = 0; } int number = c1number + c2number + carry; if (number > 1) { sb.append(number - 2); carry = 1; } else { sb.append(number); carry = 0; } } if (carry == 1) { sb.append("1"); } return sb.reverse().toString(); } }