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?
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).
一般的实现方法:鲁棒性不强,很多特殊情况没有考虑。public class Solution {
public int reverse(int x) {
int rst = 0;
while(x != 0){
rst = rst * 10 + x % 10;
x = x / 10;
}
return rst;
}
}
上述代码解决了负号问题,但是如果数字倒序后溢出,似乎没有考虑到这些情况。不具鲁棒性。也是很多人容易的犯错。应该继续修改代码,完善代码功能。
考虑到上述等特殊情况,可以先使用字符串来表示数字,然后再把之逆序,最后再以数字的形式输出。实现代码如下:
public class Solution {
public int reverse(int x){
String strX = Integer.toString(x);
int len = strX.length();
StringBuffer dest = new StringBuffer(len);
if(x>=0){
for(int i = len -1; i >= 0 ; i--){
dest.append(strX.charAt(i));
}
}
else{
dest.append('-');
for(int i = len -1; i >= 1 ; i--){
dest.append(strX.charAt(i));
}
}
<span style="white-space:pre"> </span>return Integer.parseInt(dest.toString());
}
}
讨论:
代码最后的语句:return Integer.parseInt(dest.toString());如果此时字符串表示溢出,会抛出一个异常。这似乎也不没有解决溢出问题。实际上,可以根据实际需求来提供解决方案。1.如果溢出则抛出异常。 2.使用一个extra parameter来表示数字是否溢出。 3.可以依次打印字符串中的每一个字符,这样即使数字溢出,也能表示出它的逆序。