Addition Without Carrying
Description
A little boy is studying arithmetics. He has just learned how to add two integers, written one below another, column by column. But he always forgets about the important part - carrying.
Given two integers, your task is to find the result which the little boy will get.
Note: The boy had learned from this site, so feel free to check it out too if you are not familiar with column addition.
Example
For param1 = 456
and param2 = 1734
, the output should be
additionWithoutCarrying(param1, param2) = 1180
.
456
1734
- __
1180 </code>
The boy performs the following operations from right to left:
6 + 4 = 10
but he forgets about carrying the1
and just writes down the0
in the last column5 + 3 = 8
4 + 7 = 11
but he forgets about the leading1
and just writes down1
under4
and7
.- There is no digit in the first number corresponding to the leading digit of the second one, so the boy imagines that
0
is written before456
. Thus, he gets0 + 1 = 1
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] integer param1
A non-negative integer.
Guaranteed constraints:
0 \leq param1 \le 10^5
. -
[input] integer param1
A non-negative integer.
Guaranteed constraints:
0 \leq param2 \le 6 · 10^4
. -
[output] integer
- The result that the little boy will get by using column addition without carrying.
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function additionWithoutCarrying(param1, param2) {
param1 = String(param1);
param2 = String(param2);
var a = param1.length > param2.length ? param1 : param2;
var b = param1.length > param2.length ? param2 : param1;
b = ("00000" + b)
.slice(-a.length)
.split("")
.map(Number);
a = a.split("").map(Number);
var c = a.map((el, i) => (el + b[i]) % 10);
return Number(c.join(""));
}