67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
.
Thought
Add binary with same concept in decimal, the different is carry when sum is reached to 2 instead 10. Use StringBuffer to keep the results, and insert the value at 0-index instead of appending to the last.
carry 1 1 1 1 1
A 0 1 1 0 1
+ B 1 0 1 1 1
----- -----------
A + B 1 0 0 1 0 0 = 36 (decimal)
Solution
public class Solution {
public String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
// char -> ASCII value: '0' -> 48, '1' -> 49,
// e.g., subtract '0' from '1' and we have 1
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
carry = sum / 2;
res.insert(0, String.valueOf(sum % 2));
}
if (carry == 1) res.insert(0, '1');
return res.toString();
}
}