3 回答

TA貢獻1864條經驗 獲得超6個贊
為了移動數組中的數字,以下 for 循環(huán)可用于移動數組中的值。
// prerequisite: array is already filled with values
for(int i = 0; i < numArray.length; i++) {
arr[i] += shiftNum;
if (numArray[i] > 30) {
numArray[i] -= 30;
} else if (numArray[i] <= 0) {
numArray[i] += 30;
}
}
根據您的代碼,創(chuàng)建的數組將包含 1 - 30 之間的值,包括 1 和 30。如果您希望代碼包含 0 - 29 之間的值,請將 numArray[i] > 30 更改為 numArray[i] >= 30 并將 numArray[i] <= 0 更改為 numArray[i] < 0。

TA貢獻2003條經驗 獲得超2個贊
使用 Java 的便捷方法。大多數人仍然想編寫 for 循環(huán)?;旧?,您需要保存通過轉變覆蓋的元素。然后將那些保存的放回數組中。System.arraycopy 很好,因為它可以處理數組中移動元素的一些令人討厭的部分。
void shift(int shiftBy, int... array) {
int[] holdInts = Arrays.copyOf(array, shiftBy);
System.arraycopy(array, shiftBy, array, 0, array.length - shiftBy);
System.arraycopy(holdInts, 0, array, array.length - shiftBy, holdInts.length);
}

TA貢獻1811條經驗 獲得超6個贊
這是為您提供的快速解決方案。請檢查以下代碼。
輸入 :
輸入移位/旋轉:4
輸出 :
旋轉給定數組 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
旋轉后 [27, 28, 29, 30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 , 21, 22, 23, 24, 25, 26]
public static void main(String[] args) {
RotationDemo rd = new RotationDemo();
int[] input = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
int k = 0;
Scanner scan = new Scanner (System.in);
try{
System.out.println("\nEnter the shift/rotation:");
int shiftNum = scan.nextInt();
if(shiftNum < 30) {
k = shiftNum;
System.out.println("Rotate given array " + Arrays.toString(input));
int[] rotatedArray = rd.rotateRight(input, input.length, k);
System.out.println("After Rotate " +
Arrays.toString(rotatedArray));
} else {
System.out.println("Shift number should be less than 30");
}
} catch(Exception ex){
} finally {
scan.close();
}
}
public int[] rotateRight(int[] input, int length, int numOfRotations) {
for (int i = 0; i < numOfRotations; i++) {
int temp = input[length - 1];
for (int j = length - 1; j > 0; j--) {
input[j] = input[j - 1];
}
input[0] = temp;
}
return input;
}
希望這個例子能起作用。
添加回答
舉報