我已经编写了一个将int数组向左移动的程序,但是找不到找到将其向右移动的方法。您是否可以看一下我的代码并发表评论,如果您有任何想法如何根据空格数(int x)正确“旋转”我的数组,因为当前它仅向左移动。谢谢
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while (counter < x) {
int temp = anArray[0];
for (int i = 0; i < anArray.length - 1; i++) {
anArray[i] = anArray[i + 1];
}
anArray[anArray.length - 1] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++){
System.out.print(anArray[i] + " ");
}
}
最佳答案
向右旋转数组
public void makeRight( int x )
{
int[] anArray =
{ 0, 1, 2, 3, 4, 5 };
int counter = 0;
while ( counter < x )
{
int temp = anArray[anArray.length - 1];
for ( int i = anArray.length - 1; i > 0; i-- )
{
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for ( int i = 0; i < anArray.length; i++ )
{
System.out.print( anArray[i] + " " );
}
}