YOU'VE MADE A BRAVE DECISION, WELCOME.

每一个不曾起舞的日子都是对生命的辜负。

js精度溢出

Given the string representations of two integers, return the string representation of the sum of those integers.

For example:

1
sumStrings('1','2') // => '3'

A string representation of an integer will contain no characters besides the ten numerals “0” to “9”.

方法一:
1
2
3
4
5
6
7
8
9
10
11
function sumStrings(a, b) {
var res = '', c = 0;
a = a.split('');
b = b.split('');
while (a.length || b.length || c) {
c += ~~a.pop() + ~~b.pop();
res = c % 10 + res;
c = c > 9;
}
return res.replace(/^0+/, '');
}

方法二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
function sumStrings(a,b) {
a = a.reverse(); b = b.reverse();
var carry = 0;
var index = 0;
var sumDigits = [];
while (index < a.length || index < b.length || carry != 0) {
var aDigit = index < a.length ? parseInt(a[index]) : 0;
var bDigit = index < b.length ? parseInt(b[index]) : 0;
var digitSum = aDigit + bDigit + carry;
sumDigits.push((digitSum % 10).toString());
carry = Math.floor(digitSum / 10);
index++;
}
sumDigits.reverse();
while (sumDigits[0] == '0') sumDigits.shift();
return sumDigits.join('');
}

测试结果:

precision