Traverse array in reverse, without minus sign

Viewed 240

Was asked this during a job interview today. I'm sure it's a pretty simple trick, but I couldn't think of it. How can I traverse a simple Java array from end to beginning (for example, in order to aggregate the sum of all values form right to left), without using the "minus" (-) sign (so no i-- in the loop, or something similar)?

Edit: I'm pretty sure it was supposed to be a trick that doesn't involve Java-specific structures (like Collections). Unfortunately I thought I'd think of it myself later, so I didn't ask what the answer was :/

6 Answers

Recursion is an option:

int[] numbers = {0,1,2,3,4,5,6,7,8,9,10};

public void traverseReversed(int[] a) {
    traverseReversed(a, 0);
}

private void traverseReversed(int[] a, int i) {
    if ( i + 1 < a.length ) {
        // Traverse the rest of the array first.
        traverseReversed(a, i+1);
    }
    System.out.println(a[i]);
}

public void test() throws Exception {
    System.out.println("Hello world!");
    traverseReversed(numbers);
}

If you are allowed to use Collections you can easily reverse it. Please see the below code -

Collections.reverse(Arrays.asList(array))

Don't know if the question in the interview is even a bit wise, but this answer will somehow.

Just use the ~ unary bitwise complement operator to obtain your custom -1 :

String[] array = {"aaa","bbb","ccc"};

int minusOne = ~0;// unary bitwise complement, yields -1


for(int i = array.length + minusOne; i >= 0; i = i + minusOne){

    System.out.println(array[i]);
}

If you are allowed to use library like @Naseef mentioned, you can also use Common Lang and reverse array as:

ArrayUtils.reverse(int[] array)

If you have enough stack space, you can always use recursion, and process the elements on your "way out"

void walkArray(int a[],int i){
  if(i+1<a.length)walkArray(a,i+1);
  System.out.println(a[i]);
}

EDIT, just to make sure: code would be launched as walkArray(a,0)

You can use bitwise arithmetic if you don't want to use recursion. The trick lies in the bitwise not operator. Basically it negates the number and subtracts one from it. So ~(~i+1) is the same as -(-i-1+1)-1 which simplifies to i-1.

int i = array.length;
while(i > 0) {
  i = ~(~i + 1);
  System.out.println(array[i]);
}
Related