coding
unsky
deepdim
thought

Reverse Integer 逆置int数

id7. Reverse Integer QuestionEditorial Solution My Submissions
Total Accepted: 185981
Total Submissions: 785209
Difficulty: Easy
Contributors: Admin
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.

这个题目非常简单,唯一比较麻烦得是判断溢出。

“leetcode判断溢出得方法”

  1. 设置最大最小2147483647 ~ -2147483648 在本地环境下没有问题,但是leetcode就不行了,编译环境得问题。
  2. 使用前一个结果得标志 在溢出得时候只有每次乘以10的时候会产生溢出,假设没乘以10之前的结果保存在pre_result,在乘以10之后的结果为 result,可以使用result/10!=pre_result来进行溢出判断,因为如果溢出结果就是一个溢出的数字不满足乘以10的结果。

比较啰嗦的借助了一个vector实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int reverse(int x) {
vector<int> vec;
int num;
int pre_result=0;
int result=0;
int flag=1;
if (x<=0){
num=-1*x;
flag=-1;
}
if(x>0)
num=x;
cout<<num;
while(num)
{vec.push_back(num%10);
num=num/10;
}
vector<int>::iterator it=vec.begin();
for(;it!=vec.end();it++)
{ pre_result=result;
result=result*10+(*it);
if (result/10!=pre_result)
return 0;
}
return flag*result;
}
};

精简版,不借助容器实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int reverse(int x) {
int pre_result=0;
int result=0;
while(x)
{pre_result=result;
result=result*10+x%10;
x=x/10;
if(result/10!=pre_result)
return 0;
}
return result;
}
};

坚持原创技术分享,您的支持将鼓励我继续创作!