Add Binary
Sergei Golitsynhttps://leetcode.com/problems/add-binary/
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Solution:
That is a variation of a pretty popular problem. We should calculate a sum of 2 digits. .
Also here we are going to work with bits. Ok ok.
To convert char to int we can use this approach:
int a = '1' - '0';` `
We will iterate over 2 strings at the same time. For it, we prepare 2 reader points.
Also, we will add the rest variable. Because 1 + 1 = 0 and rest = 1;
Then we just should check all cases.
NOTE. We are going to use StringBuilder. We cannot use Strings, because String in Java is immutable.
public String addBinary(String aa, String bb) {
char[] aChars = aa.toCharArray();
char[] bChars = bb.toCharArray();
int rest = 0;
int readerA = aChars.length - 1;
int readerB = bChars.length - 1;
StringBuilder sb = new StringBuilder();
while (readerA >= 0 && readerB >= 0){
int a = aChars[readerA] - '0';
int b = bChars[readerB] - '0';
int sum = a + b + rest;
rest = sum/2;
sb.append(sum % 2);
readerA--;
readerB--;
}
while(readerA >= 0){
int a = aChars[readerA] - '0';
int sum = a + rest;
rest = sum/2;
sb.append(sum % 2);
readerA--;
}
while(readerB >= 0){
int b = bChars[readerB] - '0';
int sum = b + rest;
rest = sum/2;
sb.append(sum % 2);
readerB--;
}
if (rest != 0){
sb.append(rest);
}
return sb.reverse().toString();
}