Open Tcdian opened 4 years ago
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
const maxLen = a.length > b.length ? a.length + 1 : b.length + 1;
const completedA = a.padStart(maxLen, '0');
const completedB = b.padStart(maxLen, '0');
let curry = 0;
let result = '';
for (let i = maxLen - 1; i >= 0; i--) {
const sum = Number(completedA[i]) + Number(completedB[i]) + curry;
result = String(sum % 2) + result;
curry = sum >> 1;
}
let from = 0;
while(from !== result.length - 1 && result[from] === '0') {
from++;
}
return result.slice(from);
};
function addBinary(a: string, b: string): string {
const maxLen = a.length > b.length ? a.length + 1 : b.length + 1;
const completedA = a.padStart(maxLen, '0');
const completedB = b.padStart(maxLen, '0');
let curry = 0;
let result = '';
for (let i = maxLen - 1; i >= 0; i--) {
const sum = Number(completedA[i]) + Number(completedB[i]) + curry;
result = String(sum % 2) + result;
curry = sum >> 1;
}
let from = 0;
while(from !== result.length - 1 && result[from] === '0') {
from++;
}
return result.slice(from);
};
67. Add Binary
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字
1
和0
。Example 1
Example 2
Note
'0'
或'1'
组成。1 <= a.length, b.length <= 10^4
"0"
,就都不含前导零。