Reverse digits of an integer.
Example1:
x = 123, return 321
Example2:
x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
反转整数,输入为32位有符号整数,当反转整数溢出的时候返回0。
deque<int> sk;
int max_int = INT_MAX;
class Solution {
public:
int reverse(int a) {
sk.clear();
if (a > -9 && a < 10)
return a;
int re, last = a;
bool flag = false;
if (a < 0){
last = -a;
flag = true;
}
while (last != 0){
re = last % 10;
last = last / 10;
sk.push_back(re);
}
re = 0;
while (! sk.empty()){
last = re;
if (re != 0 &&(max_int / re) < 10)
return 0;
re = re * 10 + sk.front();
sk.pop_front();
}
return flag?-re:re;
}
};
最大的问题是在于计算边界值:我是没有想到好办法,只能使用笨办法
最高效率代码:
class Solution {
public:
int reverse(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
const int max = 0x7fffffff; //int最大值
const int min = 0x80000000; //int最小值
long long sum = 0;
while(x != 0)
{
int temp = x % 10;
sum = sum * 10 + temp;
if (sum > max || sum < min) //溢出处理
{
sum = sum > 0 ? max : min;
sum=0; //让sum=0,
}
x = x / 10;
}
return sum;
}
};