ali98ab
ali98ab

Reputation: 17

function that checks if a number is narcisstic or not

I run the code multiple times but couldn't find the problem!!

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).

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

function narcissistic(value) {
  let strDigits = value.toString();
  let power = strDigits.length;
  
  let arrayDigits = strDigits.split('');
  let sum, poweredValue = 0;
  for (let i = 0; i < power; i++){
   poweredValue = Number(arrayDigits[i])**power;
    sum += poweredValue;
  }
  if (sum === value){
    return true;
  }else {
    return false;
  }
  };
  

Upvotes: 0

Views: 180

Answers (3)

Maik Lowrey
Maik Lowrey

Reputation: 17566

Something like that?

const n = 153

function action(n) {
  let sum = 0;
  n.toString().split('').forEach(i => {
    sum += parseInt(i)**n.toString().length;  
  })
  return sum == n  
}

console.log(action(n))

Upvotes: 0

Tushar Shahi
Tushar Shahi

Reputation: 20441

You assumed that the statement of the form:

let x, y =0;

initialize x and y both as 0. But x is still undefined. And type undefined + type number will evaluate to NaN (not a number). And no number is equal to NaN

Just initialize properly:

function narcissistic(value) {
  let strDigits = value.toString();
  let power = strDigits.length;
  let arrayDigits = strDigits.split('');
  let sum =0, poweredValue = 0;
  for (let i = 0; i < power; i++){
   poweredValue = Number(arrayDigits[i])**power;
    sum += poweredValue;
  }
  if (sum === value){
    return true;
  }else {
    return false;
  }
  };
  
  
  console.log(narcissistic(153));

Upvotes: 0

nullptr
nullptr

Reputation: 4474

You have to assign the initial value for sum as 0. By default, it's set to undefined. And adding something to undefined gives NaN, and any comparison with NaN is always false.

function narcissistic(value) {
  let strDigits = value.toString();
  let power = strDigits.length;

  let arrayDigits = strDigits.split("");
  let sum = 0,
    poweredValue = 0;
  for (let i = 0; i < power; i++) {
    poweredValue = Number(arrayDigits[i]) ** power;
    sum += poweredValue;
  }
  if (sum === value) {
    return true;
  } else {
    return false;
  }
}

Upvotes: 1

Related Questions