본문 바로가기
LeetCode/코딩 테스트 스터디 2주차

[LeetCode] 7. Reverse Integer 풀이 (JS)

by inwoo1324 2022. 7. 17.

0. 문제

https://leetcode.com/problems/reverse-integer/

 

Reverse Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

부호 있는 32비트 정수가 주어지면 숫자를 반전하여 반환 

#1
Input: x = 123
Output: 321
#2
Input: x = -123
Output: -321
#3
Input: x = 120
Output: 21

 

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var reverse = function(x) {
  let v = x > 0 ? 1 : -1
  x=String(Math.abs(x)).split('').reverse().join('') * v
  return x >= (2 ** 31-1) || x <= -(2 ** 31) ? 0 : x
};
Runtime: 111 ms, faster than 46.96% of JavaScript online submissions for Reverse Integer.
Memory Usage: 43.6 MB, less than 85.82% of JavaScript online submissions for Reverse Integer.
 

x 를 절대값 -> 문자열 -> 한 문자씩 끊어 배열로 치환 -> 거꾸로 뒤집기 -> 배열 합치기