# Solution For Reverse Integer

The “Reverse Integer” problem on LeetCode asks for a solution that takes an integer as an input and returns the reversed version of that integer. For example, if the input is 123, the output should be 321.

To solve this problem, we need to first understand a few things about how integer operations work in programming languages.

In most programming languages, integers are represented in binary form, which means they consist of a sequence of bits (0s and 1s). When we perform arithmetic operations on integers, we are actually manipulating these binary sequences.

One key fact about them is that we can “shift” the bits of an integer to the left or the right by a certain number of places, effectively multiplying or dividing the integer by a power of two.

For example, if we have the integer x = 123 (which is represented in binary as 01111011), we can shift its bits to the left by one place to get x * 2 = 246 (which is represented as 1111010). Similarly, we can shift its bits to the right by one place to get x // 2 = 61 (which is represented as 00111101).

With this knowledge, we can solve the “Reverse Integer” problem using the following steps:

1. Check if the input integer is negative. If it is, we will need to flip its sign before reversing the digits.

2. Initialize a variable called “reversed” to zero.

3. While the input integer is not equal to zero, do the following:

a. Get the rightmost digit of the input integer by taking the remainder of the division by 10. This gives us the digit in the ones place.

b. Multiply the “reversed” variable by 10 to shift its digits to the left by one place.

c. Add the rightmost digit from step 3a to the “reversed” variable.

d. Divide the input integer by 10 (using integer division) to remove the rightmost digit.

1. If the input integer was negative, multiply the “reversed” variable by -1 to flip its sign back.

2. If the “reversed” variable overflows the range of a 32-bit integer, return 0 (which is the behavior specified by the problem statement).

3. Otherwise, return the “reversed” variable.

Here is the Python code for this solution:

“`
class Solution:
def reverse(self, x: int) -> int:
if x < 0:
sign = -1
x *= -1
else:
sign = 1

``````    reversed = 0
while x != 0:
digit = x % 10
reversed = reversed * 10 + digit
x //= 10

reversed *= sign

if reversed < -2**31 or reversed > 2**31 - 1:
return 0
else:
return reversed
``````

“`

This code first checks if the input integer is negative and flips its sign if necessary. Then it initializes the “reversed” variable to zero and enters a loop that repeatedly extracts the rightmost digit of the input integer using the modulo operator (%), shifts the “reversed” variable to the left by multiplying it by 10, and adds the rightmost digit to the “reversed” variable. The loop continues until the input integer becomes zero.

After the loop, the code flips the sign of the “reversed” variable back if necessary and checks if it overflows the range of a 32-bit integer. If it does, the code returns 0; otherwise, it returns the “reversed” variable.

## Step by Step Implementation For Reverse Integer

```public class Solution {
public int reverse(int x) {

// check for overflow
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
return 0;
}

// convert int to string
String numStr = Integer.toString(x);

// reverse string
StringBuilder sb = new StringBuilder(numStr);
sb.reverse();

while (sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}

// check for - sign
if (sb.charAt(sb.length() - 1) == '-') {
sb.deleteCharAt(sb.length() - 1);
sb.insert(0, '-');
}

// convert string back to int
try {
return Integer.parseInt(sb.toString());
} catch (NumberFormatException e) {
return 0;
}
}
}```
```class Solution:
def reverse(self, x: int) -> int:

#converting the integer to a string
x = str(x)

#checking if the integer is negative
if x == '-':

#reversing the string
x = x[1:][::-1]

#converting the reversed string back to integer
x = int(x)

#checking if the reversed integer is in the range
if x < -2147483648 or x > 2147483647:

#if not in the range, returning 0
return 0

#if in the range, returning the negative integer
else:

return -x

#if the integer is positive
else:

#reversing the string
x = x[::-1]

#converting the reversed string back to integer
x = int(x)

#checking if the reversed integer is in the range
if x < -2147483648 or x > 2147483647:

#if not in the range, returning 0
return 0

#if in the range, returning the positive integer
else:

return x```
```var reverse = function(x) {
// convert to string
let str = x.toString();
// reverse string
let reverseStr = str.split('').reverse().join('');
// convert back to number
let reverseNum = Number(reverseStr);
// if number is greater than 2^31 - 1 or less than -2^31, return 0
if (reverseNum > (2 ** 31 - 1) || reverseNum < -(2 ** 31)) {
return 0;
}
// return reversed number
return reverseNum;
};```
```int reverse(int x) {

// Handling the edge case when the input is equal to INT_MIN which causes an overflow
if(x == INT_MIN) {
return 0;
}

// Variable to store the sign of the number
int sign = 1;

// If the input is negative, we make it positive and store the sign
if(x < 0) {
sign = -1;
x = -x;
}

// Variable to store the reverse of the number
int reverse = 0;

// Iterating through each digit of the number and reversing it
while(x > 0) {

// Handling the edge case when the reverse is going to cause an overflow
if(reverse > INT_MAX/10 || (reverse == INT_MAX/10 && x%10 > 7)) {
return 0;
}

// Adding the current digit to the reverse
reverse = (reverse*10) + (x%10);

// Removing the current digit from the number
x = x/10;
}

// Returning the reverse with the correct sign
return sign*reverse;
}```
```public class Solution {
public int Reverse(int x) {
// create a boolean to keep track of whether the number is negative or not
bool isNegative = false;
// if the number is negative, set isNegative to true and make the number positive
if (x < 0) {
isNegative = true;
x = -x;
}
// create a variable to store the reverse of the number
int reverse = 0;
// while the number is not equal to 0
while (x != 0) {
// extract the last digit of the number
int digit = x % 10;
// add the digit to the reverse
reverse = reverse * 10 + digit;
// remove the last digit from the number
x = x / 10;
}
// if the original number was negative, make the reverse negative
if (isNegative) {
reverse = -reverse;
}
// return the reverse
return reverse;
}
}```

## Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]