Reverse Integer

Monisha Mathew
2 min readMar 5, 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^31, 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

Initial thoughts:

  1. Should we use an arithmetic approach by extracting each digit in the units place and build the new integer? Seems plausible. But looks like the number automatically resets on overflow and this affects the accuracy of the solution.
  2. The next thought is of course to use a string, and reverse the string to build the result. Here is where we can be a bit picky with the implementation. A character array seems to be pretty efficient.

Approach 1:

This is a pretty straight forward question. So, let’s dive straight into different implementations. (The implementation time is indicated for each method)

/**
* Time taken - 17ms
*/
public int reverse(int x) {
int sign = 1;
if(x<0) {
sign = -1;
x = Math.abs(x); //This could slow down the code!!!
}
char[] xCharArray = String.valueOf(x).toCharArray();
int size = xCharArray.length;
char[] outCharArray = new char[size]; //Result Char Array
for(int i = 0, j = size-1; i<size; i++, j--) {
outCharArray[j] = xCharArray[i]; //Copying the digits in reverse
}
try {
return sign * Integer.parseInt(String.valueOf(outCharArray));
} catch (Exception e) {
return 0;
}
}
/////////////////////////////////////////////////////////
/**
* Time taken - 16ms
*/
public int reverse(int x) {
int sign = 1;
if(x<0) {
sign = -1;
x = x * -1; //Or Math.abs(x)
}
String outString = "";
while(x>0) {
outString+=(x%10); //extracting the units digit to build the
//reverse integer in string
x=x/10; //eliminate the used digit
}
try {
return sign * Integer.parseInt(outString);
} catch (Exception e) {
return 0;
}
}
/////////////////////////////////////////////////////////
/**
* Time taken - 15ms
*/
public int reverse(int x) {
int sign = 1;
if(x<0) {
sign = -1;
x = x * -1;
}
char[] xCharArray = String.valueOf(x).toCharArray();
int size = xCharArray.length;
char[] outCharArray = new char[size];
for(int i = 0, j = size-1; i<size; i++, j--) {
outCharArray[j] = xCharArray[i]; //copy digit array in reverse
}
try {
return sign * Integer.parseInt(String.valueOf(outCharArray));
} catch (Exception e) {
return 0;
}
}

Check out this new post for a better implementation.

Find more posts here.

Cheers & Chao!

--

--