Convert an integer to an array of digits

JavaInteger

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:

String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
    newGuess[i] = temp.charAt(i) - '0';
}

You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.

Solution 2 - Java

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[].

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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) {
    ...

Solution 8 - Java

In Javascript, this single line will do the trick:

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

Example

const numToSeparate = 12345;

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

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

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.

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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.

Solution 16 - Java

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

Solution 17 - Java

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.

Solution 18 - Java

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.

Solution 19 - Java

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

Solution 20 - Java

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

Solution 21 - Java

Without using String, Integer, ArrayList, Math:

// Actual number
int n = 56715380;
    		
    		// Copy of the number
    		int m = n;
    		
    		// Find no. of digits as length
    		int ln = 0;
    		while (m > 0) {
    			m = m / 10;
    			ln++;
    		}
    		
    		// Copy of the length
    		int len = ln;
    
    		// Reverse the number
    		int revNum = 0;
    		ln--;
    		int base;
    		while (n > 0) {
    			base = 1;
    			for (int i = 0; i < ln; i++) {
    				base = base * 10;
    			}
    			revNum = revNum + base * (n % 10);
    			n = n / 10;
    			ln--;
    		}
    
    		// Store the reverse number in the array
    		int arr[] = new int[len];
    		for (int i = 0; revNum > 0; i++) {
    			arr[i] = revNum % 10;
    			revNum = revNum / 10;
    		}
    		
    		// Print the array
    		for (int i = 0; i < arr.length; i++) {
    			System.out.print(arr[i]);
    		}

Solution 22 - Java

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.

Solution 23 - Java

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

Solution 24 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhkguileView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaVladimirView Answer on Stackoverflow
Solution 3 - JavaMarie Diana TranView Answer on Stackoverflow
Solution 4 - JavaAbhijeet srivastavaView Answer on Stackoverflow
Solution 5 - JavaJames WierzbaView Answer on Stackoverflow
Solution 6 - Javaash9View Answer on Stackoverflow
Solution 7 - JavazellioView Answer on Stackoverflow
Solution 8 - JavaJuanma MenendezView Answer on Stackoverflow
Solution 9 - JavaSkyView Answer on Stackoverflow
Solution 10 - JavaSalman SayyedView Answer on Stackoverflow
Solution 11 - JavawannikView Answer on Stackoverflow
Solution 12 - JavaNayanView Answer on Stackoverflow
Solution 13 - JavaCoderSamView Answer on Stackoverflow
Solution 14 - JavatskuzzyView Answer on Stackoverflow
Solution 15 - JavaEamonn O'Brien-StrainView Answer on Stackoverflow
Solution 16 - JavaErfanView Answer on Stackoverflow
Solution 17 - JavaPantOfflView Answer on Stackoverflow
Solution 18 - JavaRoberto GimenezView Answer on Stackoverflow
Solution 19 - JavaShadab EqbalView Answer on Stackoverflow
Solution 20 - JavaVishwa RatnaView Answer on Stackoverflow
Solution 21 - JavaBhanu DhulipudiView Answer on Stackoverflow
Solution 22 - JavaM SView Answer on Stackoverflow
Solution 23 - JavaPhilView Answer on Stackoverflow
Solution 24 - JavabhargavView Answer on Stackoverflow