Site icon

Reverse number – Leet Code Challenge

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

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

Exit mobile version