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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题意:
给一个整数,反序输出该整数,如果有符号,符号不变,假定使用32字节存储数据,如果反序后数据出现溢出,返回0;
分析:
题目比较简单,使用python几乎可以秒解此题。实现如下:
Code & Python
class Solution:
def reverse(self, x: 'int') -> 'int':
max, min= 1<<31, -1<<31 #左移和右移操作,1<<31=2^31
if x<0:
ans = -1 * int(str(-x)[::-1])
else:
ans = int(str(x)[::-1])
if ans < min or ans >= max:
return 0
return ans
Code2 & Python
class Solution:
def reverse(self, x: 'int') -> 'int':
a = str(x)[::-1]
if x<0:
res = -int(a[:-1])
else:
res = int(a)
if res<(-1<<31) or res>=2**31:
return 0
return res
以上两种写法,执行结果相同
结果:
Runtime: 48 ms, faster than 100.00% of Python3 online submissions for Reverse Integer.
Memory Usage: 12.5 MB, less than 100.00% of Python3 online submissions for Reverse Integer.
Code & C++
class Solution {
public:
int reverse(int x) {
long long imax = (1<<31)-1, imin = -imax+1, sign=1,tmp=x;
if(x<0){
tmp=-tmp;
sign=-1;
}
long long ans=0;
while(tmp){
ans = ans*10 + tmp%10;
tmp/=10;
}
if(ans<imin || ans>imax) return 0;
return sign*ans;
}
};
结果:
Runtime: 16 ms, faster than 97.40% of C++ online submissions for Reverse Integer.
Memory Usage: 14 MB, less than 100.00% of C++ online submissions for Reverse Integer.
Status:ACCEPT