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?

  • four
    I hint: it is necessary to operate with integer division and integer finding of the rest. Come on! - BuilderC

3 answers 3

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