Given a 32-bit signed integer, reverse digits of an integer.
Example
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
Easy problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution{
publicintreverse(int x) { int result = 0;
while (x != 0) { int tail = x % 10; int newResult = result * 10 + tail; if ((newResult - tail) / 10 != result) return0; result = newResult; x = x / 10; }
return result; } }
Method 1
convert to string and reverse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defreverse(self, x): """ :type x: int :rtype: int """ limit = pow(2,31) if x<0: x = abs(x) result = -int(str(x)[::-1]) else: result = int(str(x)[::-1]) if result >= (-limit) and result<=(limit-1): return result else: return0
classSolution: defreverse(self, x): """ :type x: int :rtype: int """ limit = pow(2,31) l = list(str(x)) n = len(l) for i inrange(n-1, 0 ,-1): if l[i] != '0': l = l[:i+1] break if l[0] == '-': l = l[:0:-1] l.insert(0,'-') else: l = l[::-1] result = int(''.join(l)) if result >= (-limit) and result<=(limit-1): return result else: return0