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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
public class Solution {
public int reverse(int x) {
long res = 0;
for (; x != 0; x /= 10) //一位一位进行数据处理,拿末位放首位
res = res * 10 + x % 10;
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0: (int) res;
//对最后的数据处理,溢出则返回0,不然返回数据
}
}
本文探讨了如何通过编程实现整数反转,并处理边界情况,如整数末尾为0和可能的溢出问题。
1497

被折叠的 条评论
为什么被折叠?



