# Leetcode – 7 – Reverse Integer

Reverse Integer

Reverse digits of an integer.

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

Description:

In this problem we have to reverse the integer given. for negative number the integer should be reversed with a sign.

Efficient solution: (Using Modulo and repeated division)

When we take modulo (%) of 10 for the number we will get the last digit. for ex

• 321 % 10 will give us 1
• 32 % 10 will give us 2
• 3 % 10 will give us 3

So in this case we have to do repeated modulo and store it in a variable

Also after taking modulo of the first number we will again have to get the remaining digits

321 after modulo 1 we have to get 32 we can employ division (/) for this case. Repeated division will give us the reminders

So we derive at the following logic with this

• loop until n == 0
• keep the running variable to save the intermediate values of the modulo
• every time multiply by 10 to get the correct digit places
• each iteration divide the number Code:

```public class Solution {
public int reverse(int x) {
long result = 0;
int n = x;
for(;n != 0;n /= 10){
result = result *10 + (n%10);
}
return result > Integer.MAX_VALUE || result < Integer.MIN_VALUE ? 0: (int) result;
}
}```

Time Complexity: O(n)

• Loop through the digits upto n – O(n)

Space Complexity: O(1)

• We will store the values in the result – O(1)

Available Test Cases: 1032

• Check for no input
• Check for overflow / underflow (use higher data type – long to define the results)
• Check for duplicate digits
• Check for negative number
• Check for maximum and minimum

Github:

Leetcode_7_Reverse_Integer