(Python) LeetCode 7:整数反转

题目:

代码:

class Solution:
    def reverse(self, x: int) -> int:
        s = str(x)  # 转为字符串
        length = len(s)  # 字符串长度
        index = length-1  #用作下标索引
        string = '' # 新的字符串
        if s[0] == '-':
            string += s[0]
            while index>0:
                string += s[index]
                index-=1
            if int(string) < -pow(2,31):
                return 0
            return int(string)
        else:
            while index>=0:
                string += s[index]
                index-=1
            if int(string) > pow(2,31)-1:
                return 0
            return int(string)

 

おすすめ

転載: blog.csdn.net/weixin_44260459/article/details/121291272