Sum Strings as Numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function sumStrings(a,b) {
if (a.length < b.length) { // make sure a is the longer
var tmp = a;
a = b;
b = tmp;
}
a = a.split("").reverse()
b = b.split("").reverse()
var carry = 0;
var ans = []
for (var i in a) {
if (i < b.length) {
var sumT = parseInt(a[i]) + parseInt(b[i]) + carry;
var sum = sumT % 10;
carry = (sumT - sum)/10;
ans.push(sum)
} else {
ans.push(carry + parseInt(a[i]));
carry = 0;
}
}
if (carry != 0) {
ans.push(carry);
}
return ans.reverse().join("").replace(/^0/,"")
}