Reversing a Long Number in Java

Reversing a Long Number in Java

Java program to reverse long number and print it as array

·

2 min read

In this blog post, we’ll explore how to write a Java program that reverses a long number and prints its digits as an array. We'll see step by step approach of solving this problem. First, let us look at the program:

import java.util.Scanner;
import java.lang.Math;

public class ReverseInteger {
    public static int[] digitize(long n) {
        String s = String.valueOf(n);
        int length = s.length();
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            array[i] = (int) (s.charAt(length - 1 - i)) - 48;
        }
        return array;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a long number: ");
        long val = sc.nextLong();
        int[] arr = digitize(val);
        System.out.print("Reversed number in array form: ");
        for (int digit : arr) {
            System.out.print(digit + " ");
        }
    }
}

Casting a char to int returns its ASCII value. The ASCII value for '0' is 48, so subtracting 48 from it will convert it into its proper int value.

  1. Input:

    • The user provides a long number (e.g., 698243650124).
  2. Conversion to String:

    • We convert the long number to a string. For example, if the input is 698243650124, the string representation becomes “698243650124”.
  3. Array Initialization:

    • We create an integer array with the same length as the string (in this case, 12).

    • The array will store the reversed digits of the number.

  4. Reversing the Digits:

    • We iterate through the string from left to right.

    • For each character (digit), we subtract the ASCII value of ‘0’ (which is 48) to convert it to the actual integer value.

    • We place the converted digit into the array in reverse order.

    • For example, if the input is “698243650124”, the array will contain [6, 9, 8, 2, 4, 3, 6, 5, 0, 1, 2, 4].

  5. Printing the Reversed Array:

    • Finally, we print the reversed array.

    • The output for the input “698243650124” will be:

      Reversed number in array form: 6 9 8 2 4 3 6 5 0 1 2 4

Reversing a long number and representing its digits as an array is a fundamental programming task. If you found this blog post helpful, consider following my blog BYTE WISE 010 for more programming tips, tricks, and creative content! Happy coding! 🚀📚

Did you find this article valuable?

Support Dhanush by becoming a sponsor. Any amount is appreciated!