Java - Rotating array

后端 未结 14 1121

So the goal is to rotate the elements in an array right a times. As an example; if a==2, then array = {0,1,2,3,4} would become

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 20:05

    Add a modulo array length to your code:

    // create a newArray before of the same size as array
    
    // copy
    for(int x = 0; x <= array.length-1; x++){
      newArray[(x+a) % array.length ] = array[x];
    }
    

    You should also create a new Array to copy to, so you do not overwrite values, that you'll need later on.

提交回复
热议问题