LeetCode - 007

2019-06-03 16:10:33 浏览数 (1)

原题

https://leetcode.com/problems/reverse-integer/

题干

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321 Example 2:

Input: -123 Output: -321 Example 3:

Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数的这是占字数

代码语言:javascript复制
class Solution:    def reverse(self, x: int) -> int:        if x == 0:            return 0        str_x = str(x)        x = ''        if str_x[0] == "-":            x  = "-"        x  = str_x[::-1].lstrip("0").rstrip("-")        x = int(x)        if -2**31<x<2**31-1:            return x        return 0
代码语言:javascript复制
class Solution(object):    def reverse(self, x):        """        :type x: int        :rtype: int        """        if x < 0:            return -self.reverse(-x)        res = 0        while x:            res = res * 10   x % 10            x //= 10        return res if res <= 0x7fffffff else 0

0 人点赞