一次通过,它的spoiler里面的提示有两个:
1. 末尾为0的情况,这个考虑到了
2. 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 public class Solution { 2 public int reverse(int x) { 3 int res=0; 4 int abs=Math.abs(x); 5 int updatebit=0; 6 while(abs/10!=0 || abs%10!=0){ 7 updatebit=abs%10; 8 abs=abs/10; 9 res=res*10+updatebit; 10 } 11 if(x<0){ 12 res=(-1)*res; 13 } 14 return res; 15 } 16 }
Leetcode: Reverse Integer,布布扣,bubuko.com
原文:http://www.cnblogs.com/EdwardLiu/p/3710643.html