Reverse Integer

Source

Reverse Integer Show result 

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

Example
Given x = 123, return 321

Given x = -123, return -321

Python

class Solution:
    # @param {int} n the integer to be reversed
    # @return {int} the reversed integer
    def reverseInteger(self, n):
        # Write your code here
        result=0

        sign=1
        if n<0:
            sign=-1
        n = abs(n)

        while n!=0:
            result = result*10 + n%10
            n/=10
        if result>2**31:
            return 0

        return result*sign

Java

public class Solution {
    public int reverse(int x) {
        long result=0;

        while(x!=0){
            result = result*10 + x%10;
            x/=10;
        }
        if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE){
            return 0;
        }
        return (int)result;
    }
}