Description
Reverse digits of an integer.
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.
Analysis
Two solutions are shown.
The first one may be the most average one. To reduce run time, I delete the zeroes at the end (except 0
itself) and terminate the while
loop early when the result overflows.
The second is to use string
.
The former performs better on the run time as to the test cases.
The key is how to cope with overflow. A convenient way is to store the result in a long
variable.
Code
Version 1 Math
class Solution {
public:
int reverse(int x) {
if (x == 0) return 0;
long result = 0;
while (x % 10 == 0){
x /= 10;
}
while (x){
result = result * 10 + x % 10;
if (result > INT_MAX || result < INT_MIN)
return 0;
x /= 10;
}
return result;
}
};
Version 2 String
class Solution {
public:
int reverse(int x) {
string s0 = to_string(abs(x));
string s1(s0.rbegin(), s0.rend());
long result = stol(s1);
if (x < 0) result = -result;
return (result > INT_MAX || result < INT_MIN)? 0 : result;
}
};
Appendix
- Link: https://leetcode.com/problems/reverse-integer/
- Run Time:
- Version 1: 15ms
- Version 2: 19ms