LeetCode 7
Reverse Integer
- Reference:http://blog.csdn.net/booirror/article/details/43150235
- Problem Description:
Given a 32-bit signed integer, reverse digits of an integer. - Example 1:
Input: 123 Output: 321 - Example 2:
Input: -123 Output: -321 Example 3:
Input: 120 Output: 21Solution:
class Solution {
public:
int reverse(int x) {
int reverNum = 0;
while(x != 0) {
int n = x % 10;
x = x / 10;
if (reverNum > INT_MAX/10 || reverNum < INT_MIN/10) {
% 先对reverNum进行溢出判断,如果没有先除以10,后面*10的操作可能会溢出
return 0;
}
reverNum = reverNum*10+n;
}
return reverNum;
}
};
本文介绍了一个LeetCode上的经典问题——整数反转的解决方案。通过C++实现,该算法能正确处理32位带符号整数,并考虑了溢出情况,确保了在所有边界条件下的正确性。

112

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



