Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int into an array without converting it to a String [duplicate]

Tags:

java

arrays

int

I am programming in Java and want to convert an int into an array. For example I want to convert 122 into {1, 2, 2}. Do you have an idea how this works? Thanks in advance. I am not allowed to convert it into a string.

like image 378
Z.Wo Avatar asked Mar 08 '23 15:03

Z.Wo


1 Answers

Here is the answer without using Math class

import java.util.Arrays;
class int_to_array
{
    public static void main(String arg[])
    {
        int number = 122;
        int length=0;
        int org=number;
        while(org!=0)
        {
            org=org/10;
            length++;
        }
        int[] array = new int[length];

        for(int i = 0; i < length; i++) {
          int rem = number % 10; 
          array[length - i - 1] = rem;
          number = number / 10; 
        }

        System.out.println(Arrays.toString(array));
    }
}
like image 79
Arpit Agarwal Avatar answered Mar 10 '23 09:03

Arpit Agarwal