Home / Programs / Split Integer Into Digits using Java
Programming Example

Split Integer Into Digits using Java

👁 217 Views
💻 Practical Program
📘 Step by Step Learning
This program shows the use of either Arrays or ArrayLists for accomplishing this:

Program Code

import java.util.*;

public class SplitDigits {
	public static void main(String[] args) {
		// Testing splitDigitsArrayList
		System.out.println(Arrays.toString(splitDigitsArray(123)));
		System.out.println(Arrays.toString(splitDigitsArray(40320)));
		System.out.println(Arrays.toString(splitDigitsArray(-5914133)));
		System.out.println(Arrays.toString(splitDigitsArray(0)));
		// Testing splitDigitsArray
		System.out.println(splitDigitsArrayList(123));
		System.out.println(splitDigitsArrayList(40320));
		System.out.println(splitDigitsArrayList(-5914133));
		System.out.println(splitDigitsArrayList(0));
	}

	// int --> ArrayList<Integer>
	public static ArrayList<Integer> splitDigitsArrayList(int number) {
		ArrayList<Integer> digits = new ArrayList<Integer>();
		do {
            digits.add(0, number % 10);
            number /= 10;
		} while (number != 0);
        return digits;
    }

	// int --> int[]
    public static int[] splitDigitsArray(int number) {
        int[] digits = new int[(""+Math.abs(number)).length()];
        for (int i = digits.length-1; i >= 0; i--) {
            digits[i] = number % 10;
            number /= 10;
        }
        return digits;
    }
}

Output

[1, 2, 3]
[4, 0, 3, 2, 0]
[-5, -9, -1, -4, -1, -3, -3]
[0]
[1, 2, 3]
[4, 0, 3, 2, 0]
[-5, -9, -1, -4, -1, -3, -3][0]

Explanation

e332e

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.