Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform arithmetic on the individual digits of a number

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading