Coder's Cat

LeetCode: Reverse Integer

2020-02-04

Challenge Description

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

Naive Solution

Naive solution with C++ is using mod operator to get the right-most bit of number, accumulate to a result.

Note 1: If input is 0, return 0 as result directly.

Note 2: Remember to test valid integer range in the loop, using long long for simple logic.

#define LL long long
class Solution {
public:
int reverse(int x) {
if(x == 0) return 0;
LL res = 0;
LL val = (LL)x;
while(val) {
res = res * 10 + (val % 10);
if(res > (LL)INT_MAX || res < (LL)INT_MIN)
return 0;
val /= 10;
}
return res;
}
};

If we don’t use long long type, it will be more complicated to number range validation.

class Solution {
public:
int reverse(int x) {
if(x == 0) return 0;
int res = 0;
while(x) {
if((x>0 && res <= INT_MAX/10 && res*10 <= INT_MAX - x%10) ||
(x<0 && res >= INT_MIN/10 && res*10 >= INT_MIN - x%10))
res = res * 10 + (x % 10);
else
return 0;
x /= 10;
}
return res;
}
};

Approach with string

If you don’t want the numeric operations, another approach is convert the integer into string. In this way we don’t need to care the number range issue, but need to take care the negative corner cases.

class Solution {
public:
int reverse(int x) {
bool positive = true;
string s = to_string(x);
if(s[0] == '-') {
positive = false;
s = s.substr(1, s.size()-1);
}

std::reverse(s.begin(), s.end());
long num = atol(s.c_str());
num = positive ? num : -num;

return (num > INT_MAX || num < INT_MIN) ? 0 : num;
}
};

Preparing for an interview? Check out this!

Join my Email List for more insights, It's Free!😋