Java > Array-1 > reverse3 (CodingBat Solution)

Problem:

Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.

reverse3({1, 2, 3}) → {3, 2, 1}
reverse3({5, 11, 9}) → {9, 11, 5}
reverse3({7, 0, 0}) → {0, 0, 7}


Solution:

public int[] reverse3(int[] nums) {
  int[] myArray = new int[3];
  
  myArray[0] = nums[2];
  myArray[1] = nums[1];
  myArray[2] = nums[0];
  return myArray;
}


14 comments :

  1. public int[] reverse3(int[] nums) {
    int[] a = new int[] {nums[2],nums[1],nums[0]};
    return a;
    }

    ReplyDelete
  2. public int []reverse3(int[] nums){
    return new int[] {nums[2],nums[1],nums[0]};}

    ReplyDelete
  3. int temp = nums[0];
    nums[0] = nums[2];
    nums[2] = temp;
    return nums;

    ReplyDelete
  4. public int[] reverse3(int[] nums) {
    int[] a = new int[3];
    for (int i = nums.length-1, j = 0; j < nums.length; i--, j++){
    a[j]=nums[i];
    }
    return a;
    }

    ReplyDelete
  5. return new int[] {nums [2], nums[1], nums[0]};

    ReplyDelete
  6. public int[] reverse3(int[] b) {
    int[] a=new int[3];

    a[0]= b[2];
    a[1]= b[1];
    a[2]= b[0];
    return a;
    }

    ReplyDelete
  7. int[] newReverse3 = new int[nums.length];

    for (int i = 0; i < nums.length; ++i)
    newReverse3[i] = nums[nums.length-1-i];

    return newReverse3;

    ReplyDelete
  8. public int[] reverse3(int[] nums) {
    int i ;
    i=nums[0];
    nums[0]=nums[2];
    nums[2]=i;
    return nums;

    }

    ReplyDelete
  9. public int[] reverse3(int[] nums) {
    int j = 0;

    for(int i = nums.length-1; i > 0; i--){
    int temp = nums[j];
    nums[j++] = nums[i];
    nums[i] = temp;
    }

    return nums;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact