p7

LeetCode p7 Reverse Integer 题解

1.题目:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

题意:

输入一个数字,返回它反转之后的数字,不能改变正负。
如果输出的数字大于整形大小,则输出0。

2.解题思路:

见代码,注释里面是去年左大大直播的算法课里讲过的,不过无法完成
“如果输出的数字大于整形大小,则输出0。”这个需求。
题目标签为Math 则选择数学方法。

3.代码


[title] [] [url] [link text]
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
31
32
33
 
public class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int tail = x % 10;
int c = ans * 10 + tail;
if ((c - tail) / 10 != ans)
return 0;
ans = c;
x = x / 10;
}

return ans;
}
}
// int flag = 0;
//
// if (x < 0) {
// flag = 1;
// x = -x;
// }
// String string = x + "";
// int c = (string.length() - 1) / 2;
// StringBuilder left = new StringBuilder();
// left.append(string.substring(0, c));
// StringBuilder right = new StringBuilder();
// right.append(string.subSequence(c, string.length()));
// int ans = Integer.parseInt(right.reverse().toString()
// + left.reverse().toString());
//
// return flag == 0 ? ans : -ans;


4.一些总结: