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

[Codewars] Square Every Digit (7 kyu) / JavaScript

by fluss 2022. 10. 8.

https://www.codewars.com/kata/546e2562b03326a88e000020

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice 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:

Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 9² is 81 and 1² is 1.

Note: The function accepts an integer and returns an integer

 

설명:

환영합니다. 이 카타에서는 모든 숫자의 자릿수를 제곱하고 연결해야 합니다.

예를 들어 함수를 통해 9119를 실행하면 \(9^2\)이 81 \(1^2\)이 1이므로 811181이 나올 것입니다.

참고: 함수는 정수를 받고 정수를 반환합니다.

 

풀이

function squareDigits(num){
  let result = num.toString().split('').map(el => Math.pow(parseInt(el), 2)).join('');
  return parseInt(result);
}

num을 문자열로 만들고 한 글자씩 잘라준다. 그리고 원소마다 정수로 만들어서 제곱을 해주고 다시 합친 값을 정수로 바꾸어 반환해주었다. 제곱을 할 때 정수로 바꾸는 과정 없이 Math.pow(el, 2)로 해도 el * el로 해도 답이 나온다.

댓글