Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解题思路:
将数字翻转并不难,可以转成String类型翻转,也可以逐位翻转,本题涉及到的主要是边界和溢出问题,使用Long或者BigInteger即可解决。
题目不难:
JAVA实现如下:
public class Solution {
static public int reverse(int x) {
if(x==0||x==-2147483648)return 0;
boolean isNagetive=false;
if(x<0){
isNagetive=true;
x=-x;
}
long result=0;
while(x!=0){
result*=10;
result+=x%10;
x/=10;
}
final int INT_MAX=0x7fffffff;
if((result-INT_MAX)>0)
return 0; if(isNagetive)result=-result;
return (int)result;
}
}
C++实现如下:
#include<algorithm>
using namespace std;
class Solution {
public:
int reverse(int x) {
if (x == INT_MIN)
return ;
bool isNeg = x < ;
x = abs(x);
long res = ;
while (x) {
res = res * + x % ;
if (res > INT_MAX)
return ;
x /= ;
}
return isNeg ? -(int)res: (int)res;
}
};