Clean Java solution using Java's 8 Math library for handling overflow


  • 0
    M
    public class Solution {
        public int reverse(int x) {
            int res = 0;
            do {
                try {
                    res = Math.addExact(Math.multiplyExact(res, 10), x % 10);
                }catch(ArithmeticException e) {
                    return 0;
                }
                x /= 10;
            }while(x != 0);
    
            return res;
        }
    }

Log in to reply
 

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