March-7. Integer Reversal

class Solution:
    def reverse(self, x: int) -> int:
        #取整的原因是因为 由于Python的 // 操作是向下取整,导致正负数取余 % 操作结果不一致,因此需要将原数字转为正数操作。
        #将每一位进行拆分,然后再进行组合
        y, res = abs(x), 0
        boundry = (1<<31) -1 if x>0 else 1<<31
        while y != 0:
            res = res*10 +y%10
            if res > boundry :
                return 0
            y //=10
        return res if x >0 else -res


        #利用python的字符串特性进行处理
        s = str(x)
        if s[0]=='-':
            s = s[1:]
            return  0 if -1*int(s[::-1])>2**31 or -1*int(s[::-1])<-2**31 else -1*int(s[::-1])
        else:
            return 0 if int(s[::-1])>2**31 or -1*int(s[::-1])<-2**31 else int(s[::-1])
  •  Problem analysis
    • Character string
      • Stringify integers
      • If it is a positive integer, it is directly judged to reverse the string, and then judge whether it is overflow
      • If the number is negative, extract the really reversed string, perform reverse forensics, and then judge whether it is overflow
    • Traditional disassembly and assembly
      • Take the last digit out first, and take the remainder of 10 on the original digit to get it.
      • Then perform the division operation on the original number to get the number with the last digit removed, and then continue to assemble new numbers.
      • Finally, judge whether it has overflowed or not. If it overflows directly during processing, just return 0.
      • Otherwise, it is necessary to determine the sign of the original number and select the return value

Traditional splitting actually requires absolute value operations on the original numbers during the implementation of the code. Why is this? We can see what is the result of dividing negative numbers in the language features of python.

From the result, we can see that it is rounded down, so we need to take the absolute value of the negative number to ensure that the number processed is an integer, so that there will be no deviation in the division.

 

This topic also examines a question, what if you convert a string to an integer? Take '123' as an example

 

How to split an integer, from high to position, such as 123, what is the result of the split?

Now we split the result, and then the result obtained is from the position to the high position, and the result list can be transferred to the high position to the low position. This can also be assembled back. For example, the method of solution 1.

Summary: This question not only examines the problem of data overflow, but also examines how to divide negative numbers in python, and also examines how to invert integers. You can use the language features of python, but the former solution is more general. 

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/115314167