问题
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.
回答1:
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));
}
}
回答2:
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));
回答3:
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);
来源:https://stackoverflow.com/questions/47254379/converting-an-int-into-an-array-without-converting-it-to-a-string