[java] Convert an integer to an array of digits

I try to convert an integer to an array. For example, 1234 to int[] arr = {1,2,3,4};.

I've written a function:

public static void convertInt2Array(int guess)  {
    String temp = Integer.toString(guess);
    String temp2;
    int temp3;
    int [] newGuess = new int[temp.length()];
    for(int i=0; i<=temp.length(); i++) {
        if (i!=temp.length()) {
            temp2 = temp.substring(i, i+1);
        } else {
            temp2 = temp.substring(i);
            //System.out.println(i);
        }
        temp3 =  Integer.parseInt(temp2);
        newGuess[i] = temp3;
    }

    for(int i=0; i<=newGuess.length; i++) {
        System.out.println(newGuess[i]);
    }
}

But an exception is thrown:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at q4.test.convertInt2Array(test.java:28)
at q4.test.main(test.java:14)
Java Result: 1

How can I fix this?

This question is related to java integer

The answer is


It would be much simpler to use the String.split method:

public static void fn(int guess) {
    String[] sNums = Integer.toString(guess).split("");
    for (String s : nums) {
    ...

Let's solve that using recursion...

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

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

Explanation:

Suppose the value of num is 12345.

During the first call of the function, temp holds the value 5 and a value of num = 1234. It is again passed to the function, and now temp holds the value 4 and the value of num is 123... This function calls itself till the value of num is not equal to 0.

Stack trace:

 temp - 5 | num - 1234
 temp - 4 | num - 123
 temp - 3 | num - 12
 temp - 2 | num - 1
 temp - 1 | num - 0

And then it calls the add method of ArrayList and the value of temp is added to it, so the value of list is:

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

I modified Jon Skeet's accepted answer as it does not accept negative values.

This now accepts and converts the number appropriately:

public static void main(String[] args) {
    int number = -1203;
    boolean isNegative = false;
    String temp = Integer.toString(number);

    if(temp.charAt(0)== '-') {
        isNegative = true;
    }
    int len = temp.length();
    if(isNegative) {
        len = len - 1;
    }
    int[] myArr = new int[len];

    for (int i = 0; i < len; i++) {
        if (isNegative) {
            myArr[i] = temp.charAt(i + 1) - '0';
        }
        if(!isNegative) {
            myArr[i] = temp.charAt(i) - '0';
        }
    }

    if (isNegative) {
        for (int i = 0; i < len; i++) {
            myArr[i] = myArr[i] * (-1);
        }
    }

    for (int k : myArr) {
        System.out.println(k);
    }
}

Output

-1
-2
0
-3

Try this!


int num = 1234; 

String s = Integer.toString(num); 

int[] intArray = new int[s.length()]; 


for(int i=0; i<s.length(); i++){
    intArray[i] = Character.getNumericValue(s.charAt(i));
}


I can suggest the following method:

Convert the number to a string ? convert the string into an array of characters ? convert the array of characters into an array of integers

Here comes my code:

public class test {

    public static void main(String[] args) {

        int num1 = 123456; // Example 1
        int num2 = 89786775; // Example 2

        String str1 = Integer.toString(num1); // Converts num1 into String
        String str2 = Integer.toString(num2); // Converts num2 into String

        char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
        char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char

        int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
        int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it

        for(int i=0;i<ch1.length;i++) // Watch the ASCII table
            t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want

        for(int i=0;i<ch2.length;i++) // Watch the ASCII table
            t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
        }
    }

You can use:

private int[] createArrayFromNumber(int number) {
    String str = (new Integer(number)).toString();
    char[] chArr = str.toCharArray();
    int[] arr = new int[chArr.length];
    for (int i = 0; i< chArr.length; i++) {
        arr[i] = Character.getNumericValue(chArr[i]);
    }
    return arr;
}

**** 2021 Answer ****

This single line will do the trick:

Array.from(String(12345), Number);

Example

_x000D_
_x000D_
const numToSeparate = 12345;

const arrayOfDigits = Array.from(String(numToSeparate), Number);

console.log(arrayOfDigits);   //[1,2,3,4,5]
_x000D_
_x000D_
_x000D_

Explanation

1- String(numToSeparate) will convert the number 12345 into a string, returning '12345'

2- The Array.from() method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.

3- But, in the process of automatically creating this new array, the Array.from() method will first pass any iterable element (every character in this case eg: '1', '2') to the function we set to him as a second parameter, which is the Number function in this case

4- The Number function will take any string character and will convert it into a number eg: Number('1'); will return 1.

5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.

Summary

The code line Array.from(String(numToSeparate), Number); will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.


Here is the function that takes an integer and return an array of digits.

static int[] Int_to_array(int n)
{
    int j = 0;
    int len = Integer.toString(n).length();
    int[] arr = new int[len];
    while(n!=0)
    {
        arr[len-j-1] = n % 10;
        n = n / 10;
        j++;
    }
    return arr;
}

First take input from the user as int, convert it into String, and make a character array of size of str.length(). Now populate a character array with a for loop using charAt().

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String str = Integer.toString(num);
char [] ch = new char [str.length()];

for(int i=0; i<str.length(); i++)
{
    ch[i] = str.charAt(i);
}

for(char c: ch)
{
    System.out.print(c +" ");
}

You can just do:

char[] digits = string.toCharArray();

And then you can evaluate the chars as integers.

For example:

char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // Prints 1

You don't have to use substring(...). Use temp.charAt(i) to get a digit and use the following code to convert char to int.

char c = '7';
int i = c - '0';
System.out.println(i);

I can't add comments to Vladimir's solution, but I think that this is more efficient also when your initial numbers could be also below 10.

This is my proposal:

int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
  array.add(temp % 10);
  temp /= 10;
} while  (temp > 1);

Remember to reverse the array.


temp2 = temp.substring(i); will always return the empty string "".

Instead, your loop should have the condition i<temp.length(). And temp2 should always be temp.substring(i, i+1);.

Similarly when you're printing out newGuess, you should loop up to newGuess.length but not including. So your condition should be i<newGuess.length.


public static void main(String k[])
{  
    System.out.println ("NUMBER OF VALUES ="+k.length);
    int arrymy[]=new int[k.length];
    for (int i = 0; i < k.length; i++)
    {
        int newGues = Integer.parseInt(k[i]);
        arrymy[i] = newGues;
    }
}

In Scala, you can do it like:

def convert(a: Int, acc: List[Int] = Nil): List[Int] =
  if (a > 0) convert(a / 10, a % 10 +: acc) else acc

In one line and without reversing the order.


You can do something like this:

public int[] convertDigitsToArray(int n) {

    int [] temp = new int[String.valueOf(n).length()]; // Calculate the length of digits
    int i = String.valueOf(n).length()-1 ;  // Initialize the value to the last index

    do {
        temp[i] = n % 10;
        n = n / 10;
        i--;
    } while(n>0);

    return temp;
}

This will also maintain the order.


I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.


The <= in the for statement should be a <.

BTW, it is possible to do this much more efficiently without using strings, but instead using /10 and %10 of integers.


Call this function:

  public int[] convertToArray(int number) {
    int i = 0;
    int length = (int) Math.log10(number);
    int divisor = (int) Math.pow(10, length);
    int temp[] = new int[length + 1];

    while (number != 0) {
        temp[i] = number / divisor;
        if (i < length) {
            ++i;
        }
        number = number % divisor;
        if (i != 0) {
            divisor = divisor / 10;
        }
    }
    return temp;
}

You don't need to convert int to String. Just use % 10 to get the last digit and then divide your int by 10 to get to the next one.

int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
    array.add(temp % 10);
    temp /= 10;
} while  (temp > 0);

This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].


Use:

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);
}

The main idea is

  1. Convert the int to its String value

    Integer.toString(num);
    
  2. Get a stream of int that represents the ASCII value of each char(~digit) composing the String version of our integer

    Integer.toString(num).chars();
    
  3. Convert the ASCII value of each character to its value. To get the actual int value of a character, we have to subtract the ASCII code value of the character '0' from the ASCII code of the actual character. To get all the digits of our number, this operation has to be applied on each character (corresponding to the digit) composing the string equivalent of our number which is done by applying the map function below to our IntStream.

    Integer.toString(num).chars().map(c -> c-'0');
    
  4. Convert the stream of int to an array of int using toArray()

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

Use:

int count = 0;
String newString = n + "";
char [] stringArray = newString.toCharArray();
int [] intArray = new int[stringArray.length];
for (char i : stringArray) {
  int m = Character.getNumericValue(i);
  intArray[count] = m;
  count += 1;
}
return intArray;

You'll have to put this into a method.