0%

reverse-integer

Reverse Integer – LeetCode 7

Problem

Description

Reverse digits of an integer.

Example

Example1: x = 123, return 321
Example2: x = -123, return -321

Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int reverse(int x) {
long long result = 0; bool flag = false;
if(x < 0) {x *= -1; flag = true;}
while(x > 9){
result *= 10;
result += x % 10;
x /= 10;
}
result *= 10;
result = flag?-(result + x):(result+x);
if((result > 2147483647) || (result < -2147483648))
return 0;
else
return result;
}
};

思路

用循环依次取出各位数字然后倒序输出。很标准的思路,不过要考虑到负数和溢出的问题。这里因为是int变量,所以选择使用long变量来容纳再用Int_Max和Int_Min来判断。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$12$ ms$,排名$$14.98\%$。

Better

思路

还没看到更好的思路