Reverse Integer Cont…

Monisha Mathew
1 min readMar 30, 2019

--

The question: Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2³¹, 2^(31 − 1)]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Example 1: 123

Expected Solution 1: 321

Example 2: -123

Expected Solution 2: -321

Example 3: 410

Expected Solution 3: 14

You may view the full question here.

Approach: If this is your first time checking out this question you can dabble around a little here, before we dive into this approach.

The problem was that when we tried storing the reverse value in an int type variable, on overflow the value would get reset to something else. This made it difficult to check if there was an overflow caused or not.

To overcome this problem, we store the reverse value we need to use a variable type that can hold a larger value. In our case, let’s use double type.

//Approach 2
//Runtime: 1ms
//Memory usage: 32.4MB
class Solution {
public int reverse(int x) {
int sign = 1;
if(x<0) {
sign = -1;
x = Math.abs(x);
}
double rev = 0;
while(x>0){
rev = rev*10 + x%10;
x/=10;
}
if(rev>Integer.MAX_VALUE){
return 0;
}
return sign * (int)rev;
}
}

Find more posts here.

Cheers & Chao!

--

--