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;
}
};
CodePudding user response:
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;
}
}
CodePudding user response:
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));
CodePudding user response:
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))