2014
07-22

# LeetCode-Reverse Integer

Reverse digits of an integer.

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

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).

1) 如果数字的末尾是0，如何处理？ 例如 100，输出1还是001？

2）是否要考虑溢出？例如对于int类型，1000000003 翻转后会溢出。

3）处理处理这些错误，抛出异常吗？

public class Solution {
public static int reverse(int x){
if(x==Integer.MIN_VALUE)
return Integer.MIN_VALUE;
int ans = 0;
int tmp = Math.abs(x);
while(tmp > 0){
int b = tmp % 10;
ans = ans*10 + b;
tmp /= 10;
}
return x > 0 ? ans:-ans;
}
}

1. 其实国内大部分公司对算法都不够重视。特别是中小型公司老板根本都不懂技术，也不懂什么是算法，从而也不要求程序员懂什么算法，做程序从来不考虑性能问题，只要页面能显示出来就是好程序，这是国内的现状，很无奈。