50,550
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) {
int shift = 3;
int[] arr;
arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
shiftLeft(arr, shift);
System.out.printf("向左移动%d %s%n", shift, Arrays.toString(arr));
arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
shiftRight(arr, shift);
System.out.printf("向右移动%d %s%n", shift, Arrays.toString(arr));
}
/**
* 向右移动
* 要求 arr != null && arr.length >= 1 && shift >= 0
*/
public static void shiftRight(int[] arr, int shift) {
if ((shift %= arr.length) == 0) {
return;
}
int len = arr.length;
int step = GCD(len, shift);
int round = len / step;
for (int i = 0; i < step; i++) {
int t = arr[(i + shift * round) % len], index1 = 0, index2 = 0;
for (int j = round; j > 1; j--) {
index2 = (i + shift * j - shift) % len;
index1 = (index2 + shift) % len;
arr[index1] = arr[index2];
}
arr[index2] = t;
}
}
/**
* 向左移动
* 要求 arr != null && arr.length >= 1 && shift >= 0
*/
public static void shiftLeft(int[] arr, int shift) {
if ((shift %= arr.length) == 0) {
return;
}
int len = arr.length;
int step = GCD(len, shift);
int round = len / step;
for (int i = 0; i < step; i++) {
int t = arr[i], index1 = 0, index2 = 0;
for (int j = 0; j < round - 1; j++) {
index1 = (i + shift * j) % len;
index2 = (index1 + shift) % len;
arr[index1] = arr[index2];
}
arr[index2] = t;
}
}
/**
* 辗转相除法求最大公约数
* 要求 a > 0 && b > 0
*/
public static int GCD(int a, int b) {
while (b != 0) {
int t = a;
a = b;
b = t % b;
}
return a;
}
public class Test {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
int len = arr.length;
int bits = 5;
for(int i = 0, temp; i < bits; i++) {
temp = arr[0];
for(int j = 1; j < len; j++) {
arr[j - 1] = arr[j];
}
arr[len - 1] = temp;
}
for(int i = 0; i < len; i++) {
System.out.print(arr[i]);
System.out.print('\t');
}
}
}
int[] n = new int[] { 42, 21, 2, 31 };
System.out.println("输入移动多少位:");
Scanner s = new Scanner(System.in);
int m = s.nextInt();
while(true){
if(m>n.length-1 || m<0){
System.out.println("移动位数不能大于等于数组个数,且不能移动负位!请重新输入");
m = s.nextInt();
}else{
break;
}
}
String str="";
for(int i=0;i<m;i++){
str+=n[n.length-m+i]+",";//截取m到n.length之间字符
}
for(int i=0;i<n.length-m-1;i++){//截取0到m间字符
str+=n[i]+",";
}
str+=n[n.length-m-1];
String sz[]=str.split(",");//组装后的字符再根据逗号拆分
for(int i=0;i<n.length;i++){//分别将String转换int
n[i]=Integer.parseInt(sz[i]);
}
System.out.println(Arrays.toString(n));