简体   繁体   中英

How to add to a variable when addition is in an for-loop

This is a problem from codewars . Heres my code.

function narcissistic(value) {
var total = 0
var valLength = value.length
const digit = [...`${value}`];
for(var i = 0; i < value.length; i++){
  total += Math.pow(value.length , digit)
}
  if(total == value){ return true

  } else {
    return false
  }
}

The problem I'm having is I don't why when I do total += value.length * digit[i] it isn't adding to total . Any ideas?

You can try something like this: You need to convert the function parameters into an array with different values and then calculate the power of each number and then add to the total. Also, try to use let instead of var as it is better for block-level scope.

 function narcissistic(value) { let total = 0; const digit = [...`${value}`]; for (let i = 0; i < digit.length; i++) { total += Math.pow(digit[i], digit.length); } if(total === value) { return true; } else { return false; } } console.log(narcissistic(153)); console.log(narcissistic(432));

This function can return you the required value

function narcissistic(value) {
    const stringValue = [...`${value}`];
    const len = stringValue.length;
    const sum = stringValue.reduce((prev, current) => {
        return prev + Math.pow(parseInt(current, 10), len);
    }, 0)
    return `${value}` === sum.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM