7. Reverse Integer [easy] (Python)

Topic link
https://leetcode.com/problems/reverse-integer/
The questions in the original

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

The title translation
Reverses the number in an integer.
example 1: given x=123, return 321; Example 2: Given x=-123, return -321.

If x is equal to 10 or x is equal to 100, then both returns 1. 2. What happens to overflow after the original integer is reversed?– For example, if x=1000000003, reverse overflow, then the specified overflow results will return 0.
Thinking method
Here, Python’s handling of integers doesn’t actively overflow and actually causes problems, requiring special handling.
Thinking a
Loop through the modulus of 10 to get the tail number, step by step multiply 10 to construct a new flipped integer. However, it is important to first judge the positive and negative of the original number, and finally judge whether the result is overflow.
code

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = 1 if x >= 0 else -1
        new_x, x = 0, abs(x)
        while x:
            new_x = 10 * new_x + x % 10
            x /= 10
        new_x = flag * new_x
        return new_x if new_x < 2147483648 and new_x >= -2147483648 else 0

Idea 2
Python string reversal is used to reverse an integer, and the reversed string is converted back to an integer. As above, pay attention to positive and negative and overflow situations.
code

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
        return x if x < 2147483648 and x >= -2147483648 else 0

PS: The novice brush LeetCode, the new handwriting blog, write wrong or write unclear please help point out, thank you!
reprint please indicate the: http://blog.csdn.net/coder_orz/article/details/52039990


Read More: