7. 反转整数.py

  题目链接:https://leetcode-cn.com/problems/reverse-integer/description/

  思路:先判断正负,负数转换为正数,然后将其变换为字符串,然后[::-1]进行反转就可以了

class Solution:
    def reverse(self, x):
        flag = 1
        if (x < 0):
          x = x * (-1)
          flag = 1 * (-1)
        
        ans = str(x)[::-1]
        
        ans = int (ans)
        if ans > 2147483647:
             return 0
        ans = ans * flag
        return ans
        

if __name__ == '__main__':
    s1 = Solution()
    result = s1.reverse(-1230)
    print (result)
View Code

猜你喜欢

转载自www.cnblogs.com/NaLaEur/p/9176583.html