版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyrususie/article/details/89381725
Reverse Integer
[Problem Link]
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store 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 rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
rev = rev * 10 + pop;
}
if (rev > INT_MAX || rev < INT_MIN) return 0;
return rev;
}
};
Summary
- 网上判断数值是否溢出有很多不同的方法,经对比我觉得这种最好理解,所以选择了这一种。INT型占8个字节,32位。long型占16个字节,64位。用long型计算出数值,判断是否在[INT_MIN, INT_MAX]范围内。