My simple 15-line Java code, dealing with overflow


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

Log in to reply
 

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