Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
思路:
由于js中字符串没有添加push,unshift等操作,所以先转成数组。(可以用加号拼接啊)
然后对字符串短的在前边补0,最后做进位相加
var addBinary = function(a, b) {
var res = [];
var n1 = a.length;
var n2 = b.length;
var a = a.split('');
var b = b.split('');
var carry = 0;
if (n1 < n2) {
for (var i = 0; i < n2 - n1; ++i) {
a.unshift(0);
}
}
if (n1 > n2) {
for (var i = 0; i < n1 - n2; ++i) {
b.unshift(0);
}
}
for (var i = Math.max(n1, n2) - 1; i >= 0; i--) {
var sum = Number(a[i]) + Number(b[i]) + carry;
res.unshift(sum % 2);
carry = Math.floor(sum / 2);
}
if (carry) {
res.unshift(1);
}
return res.join('')
};
不转数组做法:
var addBinary = function(a, b) {
var res = '';
var n1 = a.length;
var n2 = b.length;
// var a = a.split('');
// var b = b.split('');
var carry = 0;
if (n1 < n2) {
for (var i = 0; i < n2 - n1; ++i) {
a='0'+a;
}
}
if (n1 > n2) {
for (var i = 0; i < n1 - n2; ++i) {
b='0'+b;
}
}
for (var i = Math.max(n1, n2) - 1; i >= 0; i--) {
var sum = Number(a[i]) + Number(b[i]) + carry;
res=String(sum % 2)+res;
carry = Math.floor(sum / 2);
}
if (carry) {
res='1'+res;
}
return res
};
网友评论