Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to reverse int array

I want to optimize this solution (idiomatically).

I have a string containing only integer values. I want to convert this string into reverse int array. The output should be an integer array

Here is my solution:

private static int[] stringToReversedIntArray(String num) {
    int[] a = new int[num.length()];
    for (int i = 0; i < num.length(); i++) {
        a[i] = Integer.parseInt(num.substring(i, i + 1));
    }
    a = reverse(a);
    return a;
}

/*
 * Reverses an int array
 */
private static int[] reverse(int[] myArray) {
    int[] reversed = new int[myArray.length];
    for (int i = 0; i < myArray.length; i++) {
        reversed[i] = myArray[myArray.length - (i + 1)];
    }
    return reversed;
}

Input: "1256346258"
Output: {8,5,2,6,4,3,6,5,2,1}

Please suggest how to do same.

like image 308
Abhay Agarwal Avatar asked Jun 17 '19 06:06

Abhay Agarwal


1 Answers

var input = "1256346258";
var result = Arrays
        .stream(new StringBuffer(input).reverse().toString().split(""))
        .map(Integer::parseInt)
        .collect(Collectors.toList());
System.out.println(result);
like image 133
Rodolfo Martins Avatar answered Sep 30 '22 10:09

Rodolfo Martins