4

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.

alain
  • 11,939
  • 2
  • 31
  • 51
Z.Wo
  • 101
  • 2
  • 10

3 Answers3

3

The following example uses pure arithmetical approach (without converting the number to string):

int number = 122;
List<Integer> digitList = new LinkedList<>();

while(number > 0) {
  int d = number % 10; //get last digit
  digitList.add(0, d);
  number = number / 10; //omit last digit
}

Integer[] digits = digitList.toArray(new Integer[0]);
System.out.println(Arrays.toString(digits));
elyor
  • 998
  • 9
  • 20
  • Thanks, but I am not allowed to use math. functions - how can I do it without that? – Z.Wo Nov 12 '17 at 22:09
  • Refactor the for loop to be a recursive function which skips if your 10based index is bigger than your number – IEE1394 Nov 12 '17 at 22:11
  • Since you cannot use math you should find a method of get number of digits of the value. You can either implement your own log10 or do something like 'length=0;i=value;while(i:10>0.9){i=i/10;length++;}' – Luca Reccia Nov 12 '17 at 22:20
  • @Z.Wo I updated the code, that doesn't use Math and length of the number. – elyor Nov 12 '17 at 22:21
3

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));
    }
}
Arpit Agarwal
  • 326
  • 3
  • 15
1

This ends up in an endless loop - why that?

    int input = readInt("Bitte geben Sie eine positive Zahl ein:");
    while(input < 0) {
        input = readInt("Bitte geben Sie eine positive Zahl ein:");
    }
    int number = input;
    int length = 0;
    int org = number;
    while(org != 0) {
        org = org / 10;
        length++;
    }
    int[] inputArray = new int[length];
    int i = 0;
    while(i < inputArray.length) {
        int rem = number % 10;
        inputArray[length - i - 1] = rem;
        number = number / 10;
 i++;
    }
    String output = "{";
    i = 0;
    while(i < inputArray.length) {
        output += inputArray[i];
        if(i < inputArray.length-1) {
            output += ", ";
        }
        i++;
    }
    output += "}";
    System.out.print(output);
Arpit Agarwal
  • 326
  • 3
  • 15
Z.Wo
  • 101
  • 2
  • 10