1

I have the necessity to convert a two digits decimal number into an int array. For instance, if we suppose that I have the number 32 i would like to convert it into int[] a = new int[2] where int[0] = 3 and int[1] = 2.

3 Answers3

1

You can try with:

int x = 32;
int[] array = { x / 10, x % 10 };
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Try this:

int x, temp, i=0, j;
int[] a, b;
//Get the integer first and store in x 
//Also allocate the size of a and b with the number of digits that integer has
while(x > 0)
{
  temp = x%10;//gives remainder
  a[i] = temp;//store that value in array
  x = x/10;//to get the remaining digits
}
//the array will have the numbers from last digit

Ex:

i have x = 322

You will have the array a as { 2, 2, 3 }

 //to get the actual array try this
 j = a.length;
 while(i<j)
 {
    b[i]=a[j];
    i++;
    j--;
 }

You will have the array b as { 3, 2, 2 }

rp3220
  • 60
  • 10
0

A generalized version:

Suppose your number is stored in variable x.

final int x = 345421;
final String serialized = String.valueOf(x);
final int[] array = new int[serialized.length()];
for (int i = 0; i < serialized.length(); i++) {
    array[i] = Integer.valueOf(String.valueOf(serialized.charAt(i)));
}
Illyes Istvan
  • 569
  • 7
  • 19