본문 바로가기
알고리즘/Codewars

[Codewars] Does my number look big in this? (6 kyu) / JavaScript

by fluss 2022. 12. 15.

https://www.codewars.com/kata/5287e858c6b5a9678200083c

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

A Narcissistic Number (or Armstrong 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).

 

For example, take 153 (3 digits), which is narcisstic:

    1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

and 1652 (4 digits), which isn't:

    1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938

The Challenge:

 

Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. This may be True and False in your language, e.g. PHP.

Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function.

 

설명:

나르시시즘 수 (또는 암스트롱 수) 자신의 자릿수의 합인 양수이고, 주어진 수의 자릿수만큼 거듭제곱됩니다. 이 카타에서는 십진수로 제한합니다(십진법).

 

예를 들어, 나르시시즘 수인 153(3 자릿수)을 받으면:

    1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

그리고 그렇지 않은 1652 (4 자릿수)는:

 

    1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938

 

도전:

 

주어진 10진수의 수가 나르시시즘 수인지에 따라 true 또는 false('true'와 'false'가 아닌)를 반환해야 합니다. 언어에 따라 True와 False일수도 있습니다. 예, PHP.

유효한 0이 아닌 양의 정수만이 함수에 전달되므로 문자열이나 다른 유효하지 않은 입력에 대한 에러 체크는 불필요합니다.

 

풀이

주어진 숫자의 길이를 저장하고 숫자를 하나씩 잘라 그 수를 밑으로 하고 숫자의 길이를 지수로 한 값을 모두 더한 값이 주어진 숫자와 같다면 true를 그렇지 않다면 false를 반환했다.

 

코드

function narcissistic(value) {
  const num = String(value).split('').map(el => parseInt(el));
  let sum = 0;
  let pow = num.length;

  for(let i = 0; i < pow; i++){
    sum += num[i] ** pow;
  }
  
  if(value !== sum) return false;
  return true;
}

 

댓글