by BehindJava

How to convert an integer to an array of digits in Java

Home » java » How to convert an integer to an array of digits in Java

In this blog, we are going to learn about converting the integer to an array of digits in Java.

Get an int stream that reflects the ASCII value of each char(digit) in the String version of our number. To obtain the real int value of a character, subtract the ASCII code value of the character ‘0’ from the actual character. This procedure must be performed on each character (corresponding to the digit).

public static void main(String[] args)
{
    int num = 1234567;
    int[] digits = Integer.toString(num).chars().map(c -> c-'0').toArray();
    for(int d : digits)
        System.out.print(d);
}
  1. Convert the int to its String value.

    Integer.toString(num);
  2. Get an int stream that reflects the ASCII value of each char(digit) in the String version of our number.

    Integer.toString(num).chars();
  3. Convert the ASCII value of each character to its value. To obtain the real int value of a character, subtract the ASCII code value of the character ‘0’ from the ASCII code of the actual character. To obtain all of the digits of our number, this procedure must be performed on each character (corresponding to the digit), creating the string equivalent of our number, which is accomplished by using the map function below to our IntStream.

    Integer.toString(num).chars().map(c -> c-'0');
  4. Use toArray to convert an int stream to an int array ().

    Integer.toString(num).chars().map(c -> c-'0').toArray();

Solution using recursion…

  • Suppose the value of num is 12345.

    ArrayList<Integer> al = new ArrayList<>();

void intToArray(int num){ if( num != 0){ int temp = num %10; num /= 10; intToArray(num); al.add(temp); } }

* During the initial call of the function, temp has the value 5 and num has the value 1234. It is again supplied to the method, and this time temp has the value 4 and num has the value 123... This function is called until the value of num is greater than zero.
```json
 temp - 5 | num - 1234
 temp - 4 | num - 123
 temp - 3 | num - 12
 temp - 2 | num - 1
 temp - 1 | num - 0
  • Then it runs the add function of ArrayList and adds the value of temp to it, resulting in the value of list being:

    ArrayList - 1
    ArrayList - 1,2
    ArrayList - 1,2,3
    ArrayList - 1,2,3,4
    ArrayList - 1,2,3,4,5