Rotate an Array
Completed
Read n integers and k. Rotate the array right by k positions (k may be larger than n) and print it on one line.
Input
n, the integers, then k.
Output
One line.
Example
Input
5 1 2 3 4 5 2
Output
4 5 1 2 3
Editor
Java
Hints
Element i moves to index (i + k) % n.
Solution explanation
The modulo operator wraps indexes around the end of the array.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int k = sc.nextInt() % n;
int[] rotated = new int[n];
for (int i = 0; i < n; i++) {
rotated[(i + k) % n] = a[i];
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(rotated[i]).append(i < n - 1 ? " " : "");
}
System.out.println(sb);
}
}