Issue
There is a function that takes two arguments. The first argument is the number of digits in the number. The second argument is the number itself. (5, 12345). Arguments will be passed in this format). It is necessary to take the first and last digit of this number and add them. Then return the product of these new numbers.
Example solution ->
arguments(5, 12345)
(1+5)*(2+4)*3 = If the number of digits is odd
arguments(6, 123456)
(1+6)*(2+5)*(3+4) = If the number of digits is even
Here is the code that I wrote, for some reason it outputs NaN constantly, how to fix it and how to write conditions for the loop?
var a = prompt("Number: ");
a = Array.from(a).map(i => Number(i));
if (a.length % 2 == 0) {
result = (a[0] + a[a.length - 1]) * (a[1] + a[a.length - 2]) * (a[1] + a[a.length - 2]);
alert(result);
} else {
result = (a[0] + a[a.length - 1]) * (a[1] + a[a.length - 2]) * a[3];
alert(result);
}
Solution
You need a generic version of your solution.
Try like this:
let a = prompt("Number: ");
a = Array.from(a).map((i) => Number(i));
const n = Math.floor(a.length / 2);
let answer = a.length % 2 === 1 ? a[n] : 1;
let i = 0;
while (i < n) {
answer *= a[i] + a[a.length - (i + 1)];
i++
}
alert(answer)
Answered By - Amila Senadheera
Answer Checked By - - Terry (ReactFix Volunteer)