Very simple Java solution(No need of long)

  • 0

    While reversing, we generally do rev*10 + x%10 for every digit. There is a chance that this operation causes the overflow.
    So, before performing the above operation, we do the reverse of this operation on Integer.MAX_VALUE. This should give us a number on which if we perform the above operation, we will get the Integer.MAX_VALUE.
    Now, if the current rev value is higher than the obtained value in the previous step, then the value we will obtain by doing our rev*10 + x%10 operation will definitely be greater than Integer.MAX_VALUE. That is when we can return 0.

    public class Solution {
        public int reverse(int x) {
            int rev=0;
            int sign=1;
            int temp;
                if(rev>temp) return 0;
                rev = rev*10 + x%10;
            return rev*sign;

Log in to reply

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