Programming Example
Split Integer Into Digits using Java
This program shows the use of either Arrays or ArrayLists for accomplishing this:
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;
}
}
[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]
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.