How to Reverse an Int Array in Java

How do I reverse an int array in Java?

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

How to reverse int array Java

In the for-loop you are flipping the first number and the last number, the second number and the second-to-last number, the third number and the third-to-last number, and so on. If you go from start to the end you will flip each number twice, because you move fully though the array, and flip two numbers, therefore flipping twice the numbers in the array. You must only traverse half the array, ex:

int counter = 0;
for(int i = numArray.length-1; i >= counter; i--){
int temp = numArray[i];
numArray[i] = numArray[numArray.length - i - 1];
numArray[numArray.length - i - 1] = temp;
//print the reversed array
//System.out.print("index " + (i) + ": "+ numArray[i] + ", ");
counter++;
}

//print arr
// must be separate because must iterate the whole array
for(int i = 0; i < numArray.length; ++i){
System.out.print("Index: "+i+": "+numArray[i]+", ");
}
System.out.println(""); // end code with newline


How do I reverse an int array in Java?

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

Convert string to reverse int array

One-liner:

return IntStream
.range(0, num.length())
.map(i -> Character.getNumericValue(num.charAt(num.length() - i - 1)))
.toArray();

how to reverse a number using array in java?

I understand that you want to reverse an array... so, for that you can use ArrayUtils.reverse

ArrayUtils.reverse(int[] array)

For example, you can do:

public static void main(String[] arg){
int[] arr = { 1,2,3,4,5,6};
ArrayUtils.reverse(arr);
System.out.println(Arrays.toString(arr));
// Prints: [6, 5, 4, 3, 2, 1]
}

However, if you want to code the reverse by yourself, if you check the source code of ArrayUtils.reverse, you can find how Apache guys did it. Here the implementation:

public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}


Related Topics



Leave a reply



Submit