Reverse Integer 题解
题目来源:https://leetcode.com/problems/reverse-integer/description/
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
class Solution {
public:
int reverse(int x) {
long long res = 0;
while (x) {
res *= 10;
res += x % 10;
x /= 10;
}
return (res > INT_MAX || res < INT_MIN) ? 0 : static_cast<int>(res);
}
};
解题描述
这道题最关键需要处理的问题就是,原来的输入数字逆向输出的时候会超出int
的上限INT_MAX = 2147483647
,比如当输入为1534236469,其逆序数为9646324351,显然已经发生了溢出。所以跟atoi同理,要对输出做buffer,上面的解法就用到了long long
来做buffer,然后要对输出是否溢出做判断。