본문 바로가기
코테연습

36.Does my number look big in this?

by hxunz 2022. 4. 10.

Description:

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).

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.

 


function narcissistic(value) {
  const number = String(value).split('');
  let result = 0;
  
  for (i=0; i < number.length; i++) {
    const num = parseInt(number[i], 10);
    result += Math.pow(num, number.length)
  }
  
  return result === value ? true : false;
}

 

우선, 주어진 숫자를 string으로 바꾼다음에 숫자 하나씩 split()해서 배열로 만들었다.

const number = String(value).split('');

그 다음에는 parseInt()를 사용해서 쪼갠 숫자 하나하나 10진수로 바꾸어주었고 

const num = parseInt(number[i], 10);

Math.pow()를 사용해서 처음 주어진 숫자 길이만큼 제곱해주었다.

result += Math.pow(num, number.length)

그리고 이를 담은 값과 처음에 주어진 값이 같으면 true를 반환하고 그렇지않으면 false를 반환했다.

return result === value ? true : false;

'코테연습' 카테고리의 다른 글

38.Moving Zeros To The End  (0) 2022.04.14
37.Simple Pig Latin  (0) 2022.04.11
35.Unique In Order  (0) 2022.04.09
34.Decode the Morse code  (0) 2022.04.08
33.Tribonacci Sequence  (0) 2022.04.07

댓글