0
  1. solving Sum of Digits / Digital Root and facing problem in this case where input is 010 the output comes 8.
    please can anyone explain?
function fun(n) {
  let numString = n.toString().split("");
  let sum = 0;
  for (let i = 0; i < numString.length; i++) {
    sum += parseInt(numString[i]);
  }
  console.log(sum);
  if (sum >= 10) {
    return fun(sum);
  }
  console.log(numString);
  return sum;
}
console.log(fun(010)); // input- 010 and output- 8

Why the output is 8 but it should be 1.

OshiniRB
  • 578
  • 1
  • 7
  • 21
rmn980
  • 1
  • 4
  • because in JavaScript, a number with a leading 0 is treated as an octal, so `010` evaluates to `8` (try `console.log(010)`) – Nick Parsons Oct 07 '21 at 12:27
  • Can you send link which can explain more about it so that I can get better understanding. How can I remove this issue if vale is give like 010 or 015. – rmn980 Oct 07 '21 at 12:36
  • There are two links that explain it at the top of the post, [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#octal_numbers) is another. To deal with this issue you would need to pass your values into your function as strings to begin with: "010". – Nick Parsons Oct 07 '21 at 12:42
  • Thank You for the link and explanation. – rmn980 Oct 17 '21 at 14:28

0 Answers0