67. Add Binary
Description
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
.
Constraints
Each string consists only of
'0'
or'1'
characters.1 <= a.length, b.length <= 10^4
Each string is either
"0"
or doesn't contain any leading zero.
Approach
Links
ProgramCreek
Examples
Input: a = "11", b = "1"
Output: "100"
Solutions
/**
*
*
*/
class Solution {
public String addBinary(String a, String b) {
int alen = a.length();
int blen = b.length();
int sum = 0;
StringBuilder result = new StringBuilder("");
while(alen > 0 || blen > 0) {
if(alen > 0 && a.charAt(--alen) == '1') {
sum++;
}
if(blen > 0 && b.charAt(--blen) == '1') {
sum++;
}
result.insert(0, (sum%2));
sum /= 2;
}
if(sum == 1) {
result.insert(0, "1");
}
return result.toString();
}
}
Follow up
Last updated
Was this helpful?