# leetcode algorithm problem 016 (simple 067) binary summation

• Topic introduction
Given two binary strings, return their sum (expressed in binary).
The input is a non-empty string and contains only numbers 1 and 0.
• Example

Input: a = 11, b = 1 output: "100"

Input: a = 1010, b = 1011 output: "10101"

• Solution one
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let sum = '', i = 0, flag = '0', longStr = a.length > b.length ? a : b, shortStr = a.length > b.length ? b : a;
while(i < shortStr.length) {
if(shortStr[shortStr.length - 1 - i] === longStr[longStr.length - 1 - i]) {
sum = flag + sum;
if(shortStr[shortStr.length - 1 - i] === '1') {
flag = '1';
} else {
flag = '0';
}
} else {
sum = (flag === '1' ? '0': '1') + sum;
}
i++;
}
while(i < longStr.length) {
let c = longStr[longStr.length - 1 - i];
if(c !== flag) {
sum = '1' + sum;
flag = '0';
} else {
sum = '0' + sum;
}
i++;
}
return flag === '0' ? sum : '1' + sum;
};

Execution time: 88ms, beating 87.05% of all JavaScript submissions

Memory consumption: 35.6MB, beating 54.01% of all JavaScript submissions

• Solution two
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let sum = '',
i = a.length - 1,
flag = '0';
while (i >= 0) {
if (a[i] === b[i]) {
sum = flag + sum;
flag = (a[i] === '0' ? '0' : '1');
} else {
sum = ((flag === '0' ? '1' : '0') + sum);
}
i--;
}
return flag === '0' ? sum : '1' + sum;
};

Execution time: 92ms, beating 77.27% of all JavaScript submissions

Memory consumption: 35.7MB, beating 45.57% of all JavaScript submissions

• Be careful

If there is no cross-border problem or if you want to split strings to add, you can also convert strings to binary by bitwise operation to add and then revert back to strings.

Keywords: Javascript

Added by Smiffy on Mon, 30 Sep 2019 21:41:10 +0300