7. Reverse Integer

ooz·2021년 5월 21일
0

leetcode

목록 보기
1/1

난이도: easy

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

32비트의 정수 x가 주어질 때, 각 자릿수들을 뒤집은 x를 리턴해야 한다. 만약 뒤집은 x가 주어진 범위를 벗어나면 0을 리턴한다.

Example 1:
Input: x = 123
Output: 321

Example 2:
Input: x = -123
Output: -321

Example 3:
Input: x = 120
Output: 21

Example 4:
Input: x = 0
Output: 0

Constraints:
-231 <= x <= 231 - 1

var reverse = function(x) {
    
    if(x === 0) return x;
    
    var answer = parseInt(x.toString().split('').reverse().join(''));
    
    if(x < 0) answer *= -1;
    
    if(answer >= Math.pow(2, 31) || answer < -Math.pow(2, 31) ) return 0
    
    return answer
    
};

위처럼 작성하여 runtime 140ms, memory 40.6MB가 소요되었다.

profile
사는 것도 디버깅의 연속. feel lucky to be different🌈 나의 작은 깃허브는 https://github.com/lyj-ooz

0개의 댓글