-
Notifications
You must be signed in to change notification settings - Fork 2
/
bigNumbers.js
42 lines (40 loc) · 1 KB
/
bigNumbers.js
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
//http://www.codewars.com/kata/525f4206b73515bffb000b21/train/javascript
function add(a, b) {
var workA = [];
var workB = [];
for (var i = 0; i < a.length; i++){
workA.unshift(a[i]);
}
for (var j = 0; j < b.length; j++){
workB.unshift(b[j]);
}
var toGo = Math.max(workA.length, workB.length);
var preResult = [];
var current;
var carryOver = 0;
for (var i = 0; i < toGo; i++){
if (workA[i] && workB[i]){
current = Number(workA[i]) + Number(workB[i]) + carryOver;
}
else if (workA[i] === undefined){
current = Number(workB[i]) + carryOver;
}
else if (workB[i] === undefined){
current = Number(workA[i]) + carryOver;
}
if (current < 10){
preResult.unshift(current.toString());
carryOver = 0;
}
else {
preResult.unshift((current % 10).toString());
carryOver = 1;
}
}
if (carryOver === 1){
preResult.unshift('1');
}
var finalResult = preResult.join('');
console.log(finalResult);
return finalResult;
}