题目描述:
(C++实现)
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321lick to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
题目分析:
输入一个32位有符号的整形,返回这个数字的倒序,越界返回0。
代码实现:
class Solution {
public:
int reverse(int x) {
int y1=x,y2;
long res=0;
if(x>2147483647||x<-2147483647){
return 0;
}
while(y1!=0){
y2=y1%10;
res=res*10+y2;
//多加一个判断为了提高效率
if(res>2147483647||res<-2147483647){
return 0;
}
y1=y1/10;
}
if(res>2147483647||res<-2147483647){
return 0;
}
return res;
}
};