Leetcode

7. Reverse Integer

by hooni posted Apr 28, 2020
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


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


[문제] https://leetcode.com/problems/reverse-integer/