My simple AC java solution using long


  • 0
    M

    Compare long with Integer.MAX_VALUE to check the overflow

        public int reverse(int x) {
            int num = x > 0? x: x*-1;
            long ans = 0;
            while(num > 0){
                ans = ans * 10 + num % 10;
                num /= 10;
            }
            if(ans > Integer.MAX_VALUE){
                return 0;
            }
            ans = x > 0? ans: ans * -1;
            return (int)ans;
        }
    

Log in to reply
 

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