hkguile
hkguile

Reputation: 4359

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?

Upvotes: 77

Views: 551603

Answers (25)

Susobhan Das
Susobhan Das

Reputation: 1144

Simple Iterative

List<Integer> integerList = new ArrayList<>();
int remainder = 0;
while(n>0){
        remainder = n%10;
        n /=10;
    integerList.add(remainder);
}
int[] numArray = integerList.stream().mapToInt(x->x).toArray();

Upvotes: 0

Arun Sudhakaran
Arun Sudhakaran

Reputation: 2405

This approach will maintain the same order of the digits in the given number in the resultant array and also won't be using any collection APIs.

  1. Starting with the basic approach of reversing a number say 1234. Get the last digit by modular division (%) by 10 and then divide the number by 10 to get the last digit. Do this until the number is greater than 0.

  2. So while getting each last digit you can store it in the array, so you need to initialize an array with the same number of digits in the number, you need to use a String functionality there. But with the above step, the resulting array will be in the reverse order of the digits in your number.

  3. So start adding the number from the last index of the array to the first index.

    int num = 1234;
    int[] ar = new int[String.valueOf(num).length()];
    int index = ar.length-1;
    
    while(num > 0) {
    
        ar[index--] = num % 10;
        num = num/10;
    }
    
    System.out.println(java.util.Arrays.toString(ar));
    

Upvotes: 0

Bhanu Dhulipudi
Bhanu Dhulipudi

Reputation: 72

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

Upvotes: 0

Ali
Ali

Reputation: 485

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

Upvotes: -1

ash9
ash9

Reputation: 149

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

Upvotes: 8

M S
M S

Reputation: 1

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.

Upvotes: -1

Salman Sayyed
Salman Sayyed

Reputation: 85

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.

Upvotes: 3

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

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

Upvotes: 0

Shadab Eqbal
Shadab Eqbal

Reputation: 41

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

Upvotes: 0

James Wierzba
James Wierzba

Reputation: 17548

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

Upvotes: 5

Abhijeet srivastava
Abhijeet srivastava

Reputation: 457

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

Upvotes: 5

Roberto Gimenez
Roberto Gimenez

Reputation: 304

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.

Upvotes: 0

PantOffl
PantOffl

Reputation: 1

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.

Upvotes: 0

Sky
Sky

Reputation: 2609

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.

Upvotes: 2

Erfan
Erfan

Reputation: 143

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

Upvotes: 0

Nayan
Nayan

Reputation: 588

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

Upvotes: 1

Marie Diana Tran
Marie Diana Tran

Reputation: 593

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

Upvotes: 58

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.

Upvotes: 0

zellio
zellio

Reputation: 32484

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

Upvotes: 4

Vladimir
Vladimir

Reputation: 9753

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

Upvotes: 66

CoderSam
CoderSam

Reputation: 551

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

Upvotes: 2

bhargav
bhargav

Reputation: 1

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

Upvotes: -3

wannik
wannik

Reputation: 12706

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500685

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 <=.

Upvotes: 92

tskuzzy
tskuzzy

Reputation: 36466

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.

Upvotes: 0

Related Questions