# Solution by abernathy

• #### Solution

Intuition

Use the modulus operator to get the last digit, add that digit to reversed, and then divide x by 10 to eliminate that digit from x.

Algorithm

• Initialize reversed to the least significant digit in x
• Divide x by 10 to eliminate the least significant digit
• Use a loop to access each digit in x (once the last digit has been used, x will be 0)
• Multiply reversed by 10 to move each digit left one place and make the least significant digit 0
• Get the next digit in x by doing x % 10
• Add the digit to reversed
• Eliminate the digit you just used from x by dividing x by 10
• Return reversed

Java

``````class Solution {
public int reverse(int x) {
int reversed = x % 10;
x /= 10;
while(x != 0) {
reversed = (reversed * 10) + (x % 10);
x /= 10;
}
return reversed;
}
}
``````

Although the above code works for small numbers, there is a potential problem. The instructions stipulate that if the reversed integer causes an overflow, the function should return 0. The above code is not designed to handle overflow in this way.

An overflow can occur at the flowing places in the algorithm:

1. When reversed is being multiplied by 10 to make room for the next digit.
2. When a digit is being added to reversed.

To handle possible overflow, we can use a try catch block inside the while loop. Within the the try block we use the Math.multiplyExact and Math.addExact functions to perform the mathematical operations because they cause an AtithmeticException if the operation causes an overflow.
If an overflow occurs from either of the operations, the function goes to the catch block and returns 0.

If no overflow occurs, the function continues normally until every digit of x has been added to reversed, and returns reversed.

``````class Solution {
public int reverse(int x) {
int reversed = x % 10;
x /= 10;
while(x != 0) {
try {
reversed = Math.multiplyExact(reversed, 10);
reversed = Math.addExact(reversed, (x % 10));
x /= 10;
} catch (ArithmeticException e) {
return 0;
}
}
return reversed;
}
}
``````

Complexity Analysis

• Time complexity : O(n). We iterate through each digit in x one time
• Space complexity : O(1). Two units of space are required. One for the original int and one for the reversed int. This never changes

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.