Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class Solution { /**The program is used to calculate the sum of two binaries. This is a fundamental problem.<br> * @param a --binary string as the first operand * @param b --binary string as the second operand * @return a string --the sum of binary a and b * @author Averill Zheng * @version 2014-06-03 * @since JDK 1.7 */ public String addBinary(String a, String b) { int lengthOfA = a.length(), lengthOfB = b.length(); StringBuffer resultBuffer = new StringBuffer(); int carry = 0; while(lengthOfA > 0 && lengthOfB > 0){ int sum = (a.charAt(lengthOfA - 1) -'0') + (b.charAt(lengthOfB - 1)- '0') + carry; carry = sum / 2; resultBuffer.insert(0, sum % 2); --lengthOfA; --lengthOfB; } String remaining = (lengthOfA == 0)? b : a; int index = (lengthOfA == 0) ? lengthOfB : lengthOfA; while(index > 0){ int sum = (remaining.charAt(index - 1) -'0') + carry; carry = sum / 2; resultBuffer.insert(0, sum % 2); --index; } if(carry != 0) resultBuffer.insert(0, 1); return resultBuffer.toString(); } }