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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows
solution:
不断求和除十,注意溢出。
code:
class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x != 0){
res = res * 10 + x % 10;
x /= 10;
}
return (res > INT_MAX || res < INT_MIN) ? 0 : res;
}
};
本文介绍了一种整数翻转的算法实现,并考虑了特殊情况如输入整数的末位为0的情况以及翻转后可能产生的溢出问题。通过C++代码示例详细展示了如何避免这些问题。

828

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



