LeetCode 0007 - Reverse Integer
# Hints
- 水题
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
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: . For the purpose of this problem, assume that your function returns when the reversed integer overflows.
# 题意
给定一个正整数 ,返回将 的数位反转后的结果,如果结果超过int的表示范围则返回 。
# 题解
水题,简单循环处理即可,唯一麻烦一些的是要求特殊处理越界情况。
我们可以用long long类型强行判断越界,但这显然不是一个好主意,如果下次要求判断结果是否超过long long就没有办法了。我们有仅用int完成越界判断的方法,其实知道了就很简单,详见代码实现。
# AC代码
class Solution {
public:
int reverse(int x) {
// 求解
int res = 0;
while (x != 0) {
// 获取数位
int digit = x % 10;
x /= 10;
// 越界的情况
if (res > MAXINT / 10 || (res == MAXINT / 10 && digit > MAXINT % 10)) {
return 0;
}
if (res < MININT / 10 || (res == MININT / 10 && digit < MININT % 10)) {
return 0;
}
// 更新答案
res *= 10;
res += digit;
}
// 返回
return res;
}
// 常量
const int MAXINT = ~(1 << 31);
const int MININT = (1 << 31);
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01