문제
자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
풀이
function solution(n) {
numToString = n.toString();
let answer = [];
for(i=0; i< numToString.length; i++){
answer[i] = Number(numToString.charAt(i));
}
answer = answer.reverse();
return answer;
}
이 문제는 자릿수 더하기를 응용하여 구현했다.
https://cheese-donut.tistory.com/41?category=1045432
[코딩 테스트 연습] 자릿수 더하기
문제 자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요. 예를 들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다. 풀이 function solution(n) { const numToStri..
cheese-donut.tistory.com
Array.prototype.reverse()
reverse()는 배열의 순서를 반전시킨다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
Array.prototype.reverse() - JavaScript | MDN
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards th
developer.mozilla.org
'front-end 공부하기 > 코딩테스트' 카테고리의 다른 글
[코딩 테스트 연습] 정수 내림차순으로 배치하기 (javascript) (0) | 2022.09.28 |
---|---|
[코딩 테스트 연습] 문자열 내 p와 y의 개수 (javascript) (0) | 2022.09.27 |
[코딩 테스트 연습] 자릿수 더하기 (javascript) (0) | 2022.09.26 |
[코딩 테스트 연습] 약수의 합 (javascript) (0) | 2022.09.26 |
[코딩 테스트 연습] 평균 구하기 (javascript) (0) | 2022.09.26 |
댓글