Reverse Integer - Handling overflow


  • 0
    G
    class Solution {
        public int reverse(int x) {
            int reverseNumber = 0;
            int prevReverse =0;
            while(x != 0){
                prevReverse = reverseNumber;
                reverseNumber = (reverseNumber*10) + (x%10);
                x = x/10;
                if(reverseNumber/10 != prevReverse){
                    return 0;
                }
            }
            return reverseNumber;
        }
    }
    

    if(reverseNumber/10 != prevReverse){
    If the number is too large for datatype it can cause overflow and return a garbage value. The idea is to compare with the previous number to identify if there was an overflow at this point. If previous number and (reverseNumber/10) doesnt match return zero instead of garbage value.


Log in to reply
 

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