Reputation: 53
I am trying to write a function in Javascript that will return true
or false
depending on if the number is an Armstrong number or not. Armstrong numbers are numbers that take each digit of a number and multiple it by the length of the number, then add them all up to equal the original number. For example: 153 is an Armstrong number, because: 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
.
I'm sure my function has other problems and isn't the pretiest but I'm stuck on this.
I've already tried to add parseInt()
around multiple areas of the function to ensure that I'm only dealing with integers and not strings without any lucky.
const validate = (num) => {
const numlength = num.toString().length;
let armstrong;
let singleDigit;
for (i = 0; i < numlength; i++) {
singleDigit = num.toString()[i] ** numlength;
armstrong += singleDigit;
}
if (armstrong == num) {
return true;
} else {
return false;
}
};
console.log(validate(153))
The problem that I'm facing is that the armstrong
variable is returning NaN
for some reason. I'm not quite sure how to iteratively add the singleDigit
values that are found in the for statement. When I console.log(singleDigit)
right after it is figured out in the for statement, the value is correctly. If I console.log(armstrong)
right after that, I get NaN
Upvotes: 1
Views: 38
Reputation: 37755
You need to set initial value of armstrong = 0
.
By default it is undefined
so when you perform math operation with undefined
it results in NaN
const validate = num => {
let numString = num.toString()
const numlength = numString.length;
let armstrong = 0;
let singleDigit = 0;
for (let i = 0; i < numlength; i++) {
singleDigit = numString[i] ** numlength;
armstrong += singleDigit;
}
return armstrong == num
};
console.log(validate(153))
On side note:-
You can simply remove the last if else statement, armstrong == num
is already resulting in true
or false
Instead of calling toString()
on each iteration we can simply store in a variable and use it
One more way is to use reduce instead of for loop
const validate = num => {
let numString = num.toString()
const numLength = numString.length;
const armstrong = [...numString].reduce((acc, r) => acc += r ** numLength, 0)
return armstrong == num
};
console.log(validate(153))
Upvotes: 2