- Given a input number in java.
- Reverse input number using iterative or non recursive algorithm.
- e.g. if input number is 1234 then reverse number should be 4321.
- We will use modulus & divide operator to reverse number.
- e.g 1234 % 10 = 4
- 1234 / 10 = 123.
Examples: Reverse number in java:
Example 1:
Input number = 12345
Reverse (12345) = 54321
Example 2 (Reverse Negative number):
Input number = -5678
Reverse (-5678) = -8765
Example 3 (Reverse integer value, which would result in overflow
value :
Input number = 2147483647
Reverse (2147483647) = 0
(Reverse number would in overflow value for integer variable
(7463847412). consequently, reverse method would return 0.
Algorithm: Reverse number using module & divisor operator
- Given inputNumber 12345.
- Create variable reverseNumber = 0;
- Iterate through the loop until inputNumber > 0
- digit = 12345 % 10 = 5
- reverseNumber = reverseNumber * 10 + 5
- reverseNumber = 5
- inputNumber = inputNumber / 10.
- Keep iterative the loop
- At end of loop, we will get reverse of input number.
Program to reverse number (Leet Code Challenge)
package org.learn.beginner;
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter input number : ");
int number = scanner.nextInt();
int reverse = reverse(number);
System.out.printf("Reverse of input number %d is : %d",
number,reverse);
}
}
private static int reverse(int inputNumber) {
long reverseNumber = 0;
int digit = 0;
boolean negativeNumber = false;
if(inputNumber<0) {
negativeNumber = true;
inputNumber = Math.abs(inputNumber);
}
while(inputNumber > 0) {
//get last digit e.g. 123 % 10 = 3
digit = inputNumber % 10;
//after every loop get the next number
//which is at 10 place from current number.
reverseNumber = reverseNumber * 10 + digit;
inputNumber /= 10;
}
if(reverseNumber > Integer.MAX_VALUE ||
reverseNumber < Integer.MIN_VALUE)
return 0;
//throw new IllegalArgumentException
// ("Can not reverse input integer, Value of range");
if(negativeNumber)
reverseNumber = -reverseNumber;
return (int)reverseNumber;
}
}
Reverse input number using iterative method:
Enter input number : 12345
Reverse of input number 12345 is : 54321
Enter input number : -5678
Reverse of input number -5678 is : -8765
Enter input number : 2147483647
Reverse of input number 2147483647 is : 0