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

[LeetCode] Reverse Integer

by 오이가지아빠 2021. 3. 25.

(5) Reverse Integer - LeetCode

 

int를 입력받아서 역정렬하여 리턴하라.

 

Example 1: Input: x = 123 Output: 321

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

Example 3: Input: x = 120 Output: 21

 

간단하게 StringBuilder로 역정렬하고 음수인지 양수인지 판단해서 적절하게 바꿔주면 되는문제.

인줄 알았는데 역정렬하고 보니 Int의 범위를 벗어나는 숫자가 나오는 경우가 있다. (1,534,236,469)

 

따라서 내부 로직은 Long형으로 처리하고 Int의 범위를 벗어나면 0을 리턴하도록 마지막에 처리를 해줘야 한다.

class Solution {
    public int reverse(int x) {
        String xs = String.valueOf(x);
        String rs = new StringBuilder().append(xs).reverse().toString();
        int result = 0;
        long tempResult = 0l;
        if(rs.endsWith("-")) {
            tempResult = Long.parseLong(rs.substring(0, rs.length()-1)) * -1;
        } else {
            tempResult = Long.parseLong(rs);
        }

        if(tempResult < Integer.MIN_VALUE || tempResult > Integer.MAX_VALUE) {
            result = 0;
        } else {
            result = (int) tempResult;
        }

        return result;
    }
}

 

출처: LeetCode 
https://leetcode.com
반응형

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] Two Sum  (0) 2021.03.22

댓글