Given two binary strings, return their sum (also a binary string). For example, given a = "11" and b = "1", return "100".
public String addBinary(String a, String b) {
int m = a.length(), n = b.length();
StringBuilder result = new StringBuilder();
int carry = 0;
int i = m-1, j = n-1;
// Sum the two digits at the same position and the carry, and get the
// resulting digit in that position, and update the carry
for (; i >= 0 && j >= 0; i--, j--) {
switch (a.charAt(i)-'0'+b.charAt(j)-'0'+carry) {
case 0: result.insert(0, 0); carry = 0; break;
case 1: result.insert(0, 1); carry = 0; break;
case 2: result.insert(0, 0); carry = 1; break;
case 3: result.insert(0, 1); carry = 1; break;
}
}
// b has no digit in such significant position
for (; i >= 0; i--) {
switch (a.charAt(i)-'0'+carry) {
case 0: result.insert(0, 0); carry = 0; break;
case 1: result.insert(0, 1); carry = 0; break;
case 2: result.insert(0, 0); carry = 1; break;
}
}
// a has no digit in such sifnificant position
for (; j >= 0; j--) {
switch (b.charAt(j)-'0'+carry) {
case 0: result.insert(0, 0); carry = 0; break;
case 1: result.insert(0, 1); carry = 0; break;
case 2: result.insert(0, 0); carry = 1; break;
}
}
// Another "1" in the most significant position in case carry=1 after the above steps
if (carry == 1)
result.insert(0, 1);
return result.toString();
}
Read full article from LeetCode - Add Binary | Darren's Blog
No comments:
Post a Comment