Tell me, please, how to make an integer from an integer array whose elements are the digits of each digit of a given number in Java?
3 answers
int a = 1234; //Данное число String num = String.valueOf(a); int result[] = new int[num.length()]; //Требуемый массив for (int i = 0; i < num.length(); i++) result[i] = num.charAt(i);
- one@danpetruk: better just String.valueOf (a) .toCharArray (); - VladD
|
A recursive solution that does not create unnecessary objects on the heap during operation:
public static int[] toDigitsArray(int num) { return toDigitsArray(num, 1); } private static int[] toDigitsArray(int num, int n) { int[] digits; if (num > 10) { digits = toDigitsArray(num / 10, n + 1); } else { digits = new int[n]; } digits[digits.length - n] = num % 10; return digits; }
|
I threw in until I solved an example, mb is useful:
Extension
fun Int.toDigitArray(): List<Int> = this.toString().toCharArray().map { it.toString().toInt() }
Example:
val number = 124876 val result = number.toDigitArray() println("$result")
Result:
[1, 2, 4, 8, 7, 6]
- In the labels there seems to be nothing to decide in any language. - And
|