Description:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
My code:
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
// return parseInt((parseInt(a, 2) + parseInt(b, 2)).toString(2), 2).toString(2); 没有大整数精度处理
let arrA = a.split(''), arrB = b.split(''), carry = 0, sum = 0, arrSum = [], temp = 0;
while(arrA.length != 0 && arrB.length != 0) {
temp = parseInt(arrA.pop()) + parseInt(arrB.pop()) + carry;
arrSum.push(temp % 2);
carry =parseInt(temp / 2);
}
while(arrA.length != 0) {
temp = parseInt(arrA.pop()) + carry;
arrSum.push(temp % 2);
carry = parseInt(temp / 2);
}
while(arrB.length != 0) {
temp = parseInt(arrB.pop()) + carry;
arrSum.push(temp % 2);
carry = parseInt(temp / 2);
}
if(arrA.length == 0 && arrB.length == 0 && carry) {
arrSum.push(carry);
}
return arrSum.reverse().join('');
};
Note: 不能忘记类型转换
网友评论