Stay button (LeetCode 7) integer reversal python

topic

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:

Suppose we have an environment can only store a 32-bit signed integer, then the value range of [-231 231--1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/reverse-integer
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Thinking

Direct determination may overflow, I have we determined with digital split into 'highest to ten' × 10 + bits so were judged 'MSB - ten' is larger than the foregoing are equal when bits is greater than to determine whether the overflow on the line, the negative becomes positive number.

Code

class Solution:
    def reverse(self, x: int) -> int:
        ans=0
        maxa=2**31-1
        maxb=2**31
        flag=1
        if x<0:
            flag=-1
            x=x*-1
        while(x!=0):
            tmp=x%10
            x=x//10
            #print(tmp,x)
            if flag==1 and (ans>maxa//10 or (ans==maxa//10 and tmp>7)):
                return 0
            if flag==-1 and (ans>maxb//10 or (ans==maxb//10 and tmp>8)):
                return 0
            ans=ans*10+tmp
        return ans*flag
            

Guess you like

Origin blog.csdn.net/qq_41318002/article/details/93602344