標籤:

[leetcode algorithms]題目7

7. Reverse Integer

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

Example 1:

Input: 123Output: 321

Example 2:

Input: -123Output: -321

Example 3:

Input: 120Output: 21

Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

自己寫的代碼:

這是經典的C語言題目,不停地除以10得到每一位數字。運行時間99 ms

class Solution: def reverse(self, x): y = abs(x) res = 0 while y: res = res * 10 + y % 10 y //= 10 res = -res if x < 0 else res return res if (-2**31-1 < res < 2**31) else 0

討論區的優秀代碼:

無力吐槽

class Solution: def reverse(self, x): sign = lambda x: x and (1, -1)[x < 0] r = int(str(sign(x)*x)[::-1]) return (sign(x)*r, 0)[r > 2**31 - 1]

推薦閱讀:

[leetcode algorithms]題目18
[leetcode algorithms]題目19
Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
[leetcode algorithms]題目13
[leetcode algorithms]題目15

TAG:LeetCode |