Problem
Reverse digits of an integer.
Example
Example1: x = 123, return 321
Example2: x = -123, return -321
Algorithm
整理一下题意:给定一个整数,要求返回其数字倒序后的数。
此题比较简单,直接利用除10加模10的方法即可得到倒序。注意当给定的整数大于INT_MAX和小于INT_MIN的情况。此情况下倒序后会溢出,此时倒序结果设为0,需要特别处理。
代码如下。
class Solution {
public:
int reverse(int x) {
int temp=x,res=0;
while(temp){
if(res>214748364||res<-214748364){return 0;}
res=res*10+(temp%10);
temp=temp/10;
}
return res;
}
};