Reverse Integer in Java. - CodeByAkram

Reverse Integer in Java.

Algorithm 


Reversing Integer is very easy, start collecting the digits from the back of the number until no digits is remaining.

How we will get the last digit of a number?
when a number is Mod by 10, we will get the last digit of a number. 
Example  int lastDigit = number % 10.

We just collected the last digit, so now we need to get the remaining number to work on except the last digit which we already worked on, how we will get the remaining number except last digit?
By dividing the number by 10. Example: int remainingNumber = number / 10.

We need to collect all the last digits we get in reverse order, how to do that?
int reversedNumber = reversedNumber * 10 + lastDigit;

Continue above steps in loop  until remaining number is 0.

Note: We may hit integer overflow when we do (reversedNumber * 10 + lastDigit), so make sure before executing that line we check for overflow.

1. reversedNumber * 10 can overflow, so check reversedNumber  > Integer.MAX_VALUE / 10, if yes then (reversedNumber * 10) will surely overflow.

2. reversedNumber * 10 + lastDigit
Adding the + lastDigit can also overflow, if reversedNumber is exactly equal to Integer.MAX_VALUE / 10 then we need to check the + lastDigit we add should be less that 7 (for positive number) because in Java, the integer ranges from -2,147,483,648 to +2,147,483,647 and greater than -8 in case negative number.

No comments:

Post a Comment