GuoXin Li's Blog

LeetCode 7.Reverse Integer

字数统计: 205阅读时长: 1 min
2020/09/22 Share

7. Reverse Integer

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: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x != 0){
int pop = x % 10;
x /= 10;
if(ans > INT_MAX / 10 || ans == INT_MAX / 10 && pop > 7 ) return 0;
if(ans < INT_MIN / 10 || ans == INT_MIN / 10 && pop < -8 ) return 0;
ans = ans * 10 + pop;
}
return ans;
}
};

Explanation:

#define INT_MAX = 2147483647

#define INT_MAX = -INT_MAX-1

也就是关于int的最大值和最小值的说明

将一个数字进行反转,从个位数进行取,使用取余的方法,再使用“余数X10”进行往高位移动。

这个过程中需要注意溢出时的条件即可。

CATALOG
  1. 1. Solution