Title: There are n integers, so that they move backward in the order of the first number of M positions, the last m number becomes the first number of M
Original array:
[2, 3, 4, 6, 7, 9]
Please enter the number of digits to move: 3
[6, 7, 9, 2, 3, 4]
The length of the array is limited, and the elements moving beyond the length of the array are re-queued in front of the array
Method One, record the location of the move
For example, the overall backward two-bit, that is, the index of 7,9 to become 0, 1; And the index of 2,3,4,6 to add 2; The length of the array len=6, using this relationship, we write a method
Public Static voidfunction () {int[] array={2,3,4,6,7,9}; //copy an array for storing the data int[] arraycopy=arrays.copyof (array, array.length); //define the number of bits moved//Index intlen=Array.Length; System.out.println ("Original array:"); System.out.println (arrays.tostring (array)); System.out.println ("Please enter the number of digits to move:"); Scanner SC=NewScanner (system.in); intmovenum=Sc.nextint (); intPoint=len-movenum;//6-2=4 for(inti = 0; i < Array.Length; i++) { if(i<Point ) {Arraycopy[i+movenum]=array[i];//Exchange Index Values } if(i>=Point ) {Arraycopy[i-point]=array[i];//Exchange Index Values}} System.out.println ("After move:"); System.out.println (arrays.tostring (arraycopy)); }
Method 2, you can use the length of the array, using the same principle to dynamically change the index of each element of the array changes
1 //Dynamic index New index value = (original index + moving digit)% array length, move right to understand overflow, length is a loop2 Public Static voidFunction01 () {3 int[] array={2,3,4,6,7,9};4 //copy an array for storing the data5 int[] arraycopy=arrays.copyof (array, array.length);6System.out.println ("Original array:");7 System.out.println (arrays.tostring (array));8System.out.println ("Please enter the number of digits to move:");9Scanner sc=NewScanner (system.in);Ten One intMovenum=sc.nextint ();//number of bits moved A - for(inti = 0; i < arraycopy.length; i++) { - intMove= (i+movenum)%Array.Length; thearraycopy[move]=Array[i]; - } - System.out.println (arrays.tostring (arraycopy)); - + -}
Move the position of an array element