题目链接:https://leetcode.com/problems/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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
int reverse(int x) {
long long ret = 0;
int digit;
while(x) {
digit = x > 0 ? x % 10 : -(-x) % 10;
ret = 10 * ret + digit;
if(ret > 2147483647 || ret < -2147483648)
return 0;
x /= 10;
}
return ret;
}
本文介绍了一个简单的整数反转算法,并提供了详细的实现代码。通过该算法,可以将输入的整数进行位反转操作,例如123变为321。文章还讨论了特殊情况处理,如反转后的整数溢出及末尾为0的情况。
280

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



