use java1.8 api


  • 0
    A

    Here is a code using Java1.8 API using which we can check for overflows.

    public int reverse(int x) {
    		int reverse = 0;
    		try{
    		while (Math.abs(x) > 0) {
    			reverse = Math.addExact(reverse, x % 10);
    			x = x / 10;
    			if (Math.abs(x) > 0)
    				reverse = Math.multiplyExact(reverse, 10);
    		}
    		}catch(ArithmeticException e){
    			return 0;
    		}
    		return reverse;
    	}
    

    Hope it helps.


Log in to reply
 

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