Java solution. I provide a good way to check overflow


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

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.