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

Error in true false output in Array Problem

Here’s the question:

A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits), which is narcisstic:

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

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Your code must return true or false (not ‘true’ and ‘false’) depending upon whether the given number is a Narcissistic number in base 10.

My Code is:

function narcissistic(value) {
  let vLen = value.length;
  let sum = 0;
  for (let i = 0; i < vLen; i++) {
    sum += Math.pow(value[i], vLen);
  }
  if (sum == value) {
    return true;
  } else {
    return false;
  }
}

But I’m getting errors. What should I do?

>Solution :

  1. Numbers don’t have .length, convert to string first
  2. vLen[i], you cant treat a number as array, again, convert to string to use that syntax.
  3. The return can be simplefied to return (sum === value);
function narcissistic(value) {
  let sVal = value.toString();
  let vLen = sVal.length;
  
  let sum = 0;
  for (let i = 0; i < vLen; i++) {
    sum += Math.pow(sVal[i], vLen);
  }
  
  return (sum === value);
}

console.log(narcissistic(153));
console.log(narcissistic(111));
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