问题描述
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
问题分析
翻转int,主要考点在于怎么处理正负和溢出。
代码实现
public int reverse(int x) {
if (x == 0) return 0;
String num = String.valueOf(x);
int inx = 0;
boolean minus = false;
if (num.charAt(0) == '-') {
minus = true;
inx++;
}
long result = 0;
int flag = 1;
if (minus) flag = -1;
for (int i = num.length() - 1; i >= inx; i--) {
result = result * 10 + flag * (num.charAt(i) - '0');
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0;
}
return (int) result;
}
网友评论