Friday, November 4, 2016

Leetcode 7 : Reverse Integer Solution

Problem statement could be found @https://leetcode.com/problems/reverse-integer/

Analysis -

The solution (code)  to this problem is very simple, but there are two points should be taken care of -

1. While reversing a integer, there  might be an overflow ie reversed integer might not fit into an integer value, so to store the reversed value  in a long variable.
2. Once the final value is calculated, check whether it fits in integer range or not. If not, then return 0


class Solution {
public:
    int reverse(int x) {
       long rev=0;
       
        while (x != 0){
            rev = (rev * 10) + x%10;
            x = x/10;
        }
        if( (rev > INT_MAX) || (rev < INT_MIN))
            rev = 0;
        return rev;  
    }
};