본문 바로가기

Leetcode 100문제 도전

[Leetcode 3/100] Reverse Integer - Easy

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

문자열로 푸는 방식

class Solution {
    public int reverse(int x) {
        
        String reversed = new StringBuilder().append(Math.abs(x)).reverse().toString();
        
        try{
            return ( x < 0 ) ? Integer.parseInt(reversed) * - 1 : Integer.parseInt(reversed);
        } catch (NumberFormatException e){
            return 0;
        }
        
    }
}

숫자를 이용하는 방식

class Solution {
    public int reverse(int x) {
        
        int result = 0;
        
        while( x != 0){
            
            result = result * 10 + x % 10;
            x = x/10;
            
        }
        
        if(result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
            return 0;
        } else {
            return (int)result;
        }
        
    }
}