Java > Array-1 > rotateLeft3 (CodingBat Solution)

Problem:

Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.

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


Solution:

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

2 comments:

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

    ReplyDelete
  2. public int[] rotateLeft3(int[] nums) {
    int i ;
    i = nums[0];
    nums[0]= nums[1];
    nums[1]= nums[2];
    nums[2]=i;
    return nums;
    }

    ReplyDelete