-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumStringAsNumber.js
More file actions
47 lines (39 loc) · 923 Bytes
/
Copy pathSumStringAsNumber.js
File metadata and controls
47 lines (39 loc) · 923 Bytes
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// URL: https://www.codewars.com/kata/5324945e2ece5e1f32000370
// Description
/*
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
*/
// Code
function sumStrings(a,b) {
if (a.length < b.length) {
while (a.length != b.length){
a = '0' + a;
}
} else if (b.length < a.length) {
while (b.length != a.length) {
b = '0' + b;
}
}
let sum = '';
let carry = 0;
for (let i = a.length - 1; i >= 0; i--) {
const aNum = +a[i];
const bNum = +b[i];
const innerSum = aNum + bNum + carry;
let placeNum = innerSum;
if (innerSum > 9) {
placeNum = innerSum % 10;
carry = Math.floor(innerSum / 10);
} else {
carry = '';
}
sum = placeNum + sum;
}
sum = carry + sum;
while (sum[0] == '0') {
sum = sum.slice(1);
}
return sum;
}