class Solution {
public String addBinary(String a, String b) {
int len1 = a.length() - 1;
int len2 = b.length() - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (len1 >= 0 || len2 >= 0){
int sum = carry;
if (len1 >= 0) sum += a.charAt(len1) - '0';
if (len2 >= 0) sum += b.charAt(len2) - '0';
sb.append(sum%2);
carry = sum/2;
len1--;
len2--;
}
if(carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}
Apparently, this code works for the solution, I'm just having a hard time understanding the question. For this line:
sum += a.charAt(len1) - '0';
sum is an integer, a.charAt(len1) returns a char, how can it perform addition between an integer and a char? also, what does it mean to - '0'?