JAVA#数组内元素的反转'小节
程序员文章站
2022-03-16 10:57:44
...
事情开始之前,先来解释下什么叫反转:321===>123,将其顺序颠倒个遍便是反转。
1.常规操作
所谓常规操作,就是我奶奶也会的那种操作;
来了:
public class Turnover {
public static void main(String[] args) {
String[] NBAplayer = new String[]{"Allen Iverson", "Kobe Bryant", "Michael Jordan"};
for(int i = 0; i<NBAplayer.length;i++)
{
System.out.println(NBAplayer[i]);
}
for(
int i = 0;
i<NBAplayer.length/2;i++)
{
String temp = NBAplayer[i];
NBAplayer[i] = NBAplayer[NBAplayer.length - 1 - i];
NBAplayer[NBAplayer.length - 1 - i]=temp;
}
for(
int i = 0;
i<NBAplayer.length;i++)
{
System.out.println(NBAplayer[i]);
}
}
}
编译运行:
Allen Iverson
Kobe Bryant
Michael Jordan
Michael Jordan
Kobe Bryant
Allen Iverson
如上便是Turnover的常规操作;
2.AI Crossover操作
通过位运算符的学习,我们知道翻转数组元素还可以采用另一种骚气的方法;
来了:
public class Turnover {
public static void main(String[] args) {
int[] NBAplayer = new int[]{3,23,24,19941112};
for(int i = 0; i<NBAplayer.length;i++)
{
System.out.println(NBAplayer[i]);
}
for(
int i = 0;
i<NBAplayer.length/2;i++)
{
NBAplayer[i]=NBAplayer[i]^NBAplayer[NBAplayer.length-i-1];
NBAplayer[NBAplayer.length-i-1]=NBAplayer[i]^NBAplayer[NBAplayer.length-i-1];
NBAplayer[i]=NBAplayer[i]^NBAplayer[NBAplayer.length-i-1];
}
System.out.println("下面开始艾弗森CROSSOVER集锦表演");
for(
int i = 0;
i<NBAplayer.length;i++)
{
System.out.println(NBAplayer[i]);
}
}
}
编译运行:
3
23
24
19941112
下面开始艾弗森CROSSOVER集锦表演
19941112
24
23
3
上一篇: ThinkPHP框架让页面重定向方法总结