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"
从低位到高位按位做加法,注意处理进位。
class Solution {
public String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
String result = "";
while(i >= 0 && j >= 0) {
int sum = a.charAt(i) + b.charAt(j) + carry - 96;
carry = sum / 2;
sum = sum % 2;
result = sum + result;
i--;
j--;
}
while (i >= 0) {
int sum = a.charAt(i) + carry - 48;
carry = sum / 2;
sum = sum % 2;
result = sum + result;
i--;
}
while(j >= 0) {
int sum = b.charAt(j) + carry - 48;
carry = sum / 2;
sum = sum % 2;
result = sum + result;
j--;
}
if(carry == 1) {
result = "1" + result;
}
return result;
}
}