narcissistic.js

Codewars 알고리즘 풀이


Problem

  • A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits in a given base.
    • Narcissistic Number는 주어진 숫자의 자릿수만큼 제곱되는 각 자릿수의 합계인 숫자이다.
  • In this Kata, we will restrict ourselves to decimal(base 10).
    • 이 Kata에서는 10진수(10진법)으로 제한한다.
  • Your code must return ‘true’ or ‘false’ depending upon whether the given number is Narcissistic number in base 10.
    • 주어진 숫자가 10진법 Narcissistic Number인지에 따라 ‘true’ 또는 ‘false’를 반환한다.



Solution 01

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

narcissistic(153);   // true (1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153)
narcissistic(1634);  // true (1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634)


Solution 02

function narcissistic(n) {
  let str = n + '';
  let sum = 0;
  
  for (let i = 0; i < str.length; i++) {
    sum += Math.pow(parseInt(str[i]), str.length);
  }
  
  return sum === n;
}

narcissistic(153);   // true (1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153)
narcissistic(1634);  // true (1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634)


Solution 03

function narcissistic(n) {
  return n.toString().split('').reduce((sum, i) => {
    return sum + Math.pow(i, n.toString().length);
  }, 0) === n;
}

narcissistic(153);   // true (1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153)
narcissistic(1634);  // true (1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634)