Reverse Integer

Problem: Reverse Integer

This problem becomes simple comes to python. Just convert the integer to string and reverse the string. We still need to deal with negative numbers and overflow numbers.

Code in Python:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        MAX = 2**31-1
        x = str(x)
        if x[0] == "-": neg, x = True, x[:0:-1]
        else: neg, x = False, x[::-1]
        if int(x) > MAX: return 0
        elif neg: return -1*int(x)
        else: return int(x)

Besides, we can also use simple calculation to decide whether a number is overflow if there is a limit on integer in some languages.

Code in Java:

public class Solution {
    public int reverse(int x) {
        if (x == 0)
            return x;

        int symbol = 1;
        if (x < 0) {
            symbol = -1;
            x = -x;
        }

        int res = 0;
        while (x != 0) {
            if ((res*10+x%10-x%10)/10 != res)
                return 0;
            int digit = x % 10;
            res = res * 10 + digit;
            x /= 10;
        }

        return symbol * res;
    }
}

results matching ""

    No results matching ""