题目描述
题目链接:7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
例子
例子 1
Input: 123 Output: 321
例子 2
Input: -123 Output: -321
例子 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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解题思路
题目比较简单,只需要不断求余数即可,注意由于正负数转化的问题我们需要先将 x
转为长整形避免溢出,对结果变量也是一样。代码如下:
#include <cmath>
class Solution {
public:
int reverse(int x) {
long rev = 0;
long copy = x;
bool is_negative = copy < 0;
copy = copy > 0 ? copy : -copy;
while (copy) {
rev *= 10;
rev += (copy % 10);
copy /= 10;
}
if (is_negative) rev = -rev;
if (rev < -1 * pow(2, 31) || rev > pow(2, 31) - 1) return 0;
return rev;
}
};
- 时间复杂度: O(digits of
x
) - 空间复杂度: O(1)
GitHub 代码同步地址: 7.ReverseInteger.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions