67. 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"
注意进位。
solution1:
class Solution {
public String addBinary(String a, String b) {
int carry = 0;
int aDigit = 0;
int bDigit = 0;
StringBuilder result = new StringBuilder();
for(int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >=0; i--, j--) {
aDigit = (i > -1) ? a.charAt(i) - '0' : 0;
bDigit = (j > -1) ? b.charAt(j) - '0' : 0;
result.append((carry + aDigit + bDigit) % 2); // Appends String rep of int argument
carry = (carry + aDigit + bDigit) / 2;
}
if(carry > 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
It's just like in Add TwoNumbers, we add from the last digits of two numbers and keep update carry.
Remember to care the last carry digit.
Then reverse and return.

浙公网安备 33010602011771号