黑马程序员技术交流社区
标题:
代码优化
[打印本页]
作者:
zhangx
时间:
2013-4-12 21:45
标题:
代码优化
本帖最后由 zhangx 于 2013-4-13 10:54 编辑
假如不要java类库,这段代码怎么优化啊?
public class Demo{
public static void main(String args[]){
int score[]=null;
score=new int[10];
for(int i=0;i<10;i++){
score
=i ;
System.out.print(score
+(i==9?"":","));
}
System.out.println();
for(int i=0;i<5;i++){
int temp=0;
temp=score
;
score
=score[9-i];
score[9-i]=temp;
}
for(int j=0;j<10;j++){
System.out.print(score[j]+(j==9?"":","));
}
}
}
作者:
李芳池
时间:
2013-4-12 22:19
class Demo{
public static void main(String[] args){
int[] score=new int[10];
for (int i=0;i<score.length;i++){
score[i]=i;
}
print(score);
reverseArray(score);
System.out.println("反转后的数组:");
print(score);
}
private static void reverseArray(int[] arr){
for (int start=0,end=arr.length-1;start<end;start++,end-- ){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
public static void print(int[] arr){
for (int i=0;i<arr.length ;i++ ){
System.out.print(arr[i]+(i==9?"":","));
}
System.out.println();
}
}
复制代码
作者:
何俊森
时间:
2013-4-12 22:26
这里说到优化,只能把临时变量temp的空间节省掉了吧。
public class Demo01 {
public static void main(String args[]) {
int score[] = null;
score = new int[10];
for (int i = 0; i < 10; i++) {
score[i] = i;
System.out.print(score[i] + (i == 9 ? "" : ","));
}
System.out.println();
for (int i = 0; i < 5; i++) {
score[i] ^= score[9 - i];
score[9 - i] ^= score[i];
score[i] ^= score[9 - i];
}
for (int j = 0; j < 10; j++) {
System.out.print(score[j] + (j == 9 ? "" : ","));
}
}
}
复制代码
作者:
杨永胜
时间:
2013-4-12 22:26
面向对象编程,代码就简单多了,2楼正确
作者:
杨永胜
时间:
2013-4-12 22:26
面向对象编程,代码就简单多了,2楼正确
作者:
刘策
时间:
2013-4-12 22:40
public class Demo{
public static void main(String[] args){
int[] score = new int[10];
for(int i=0;i<5;i++){
if(i==0){
for(int x=0;x<10;x++){
score[x]=x;
System.out.println(score[x]+(i==9?"":","));
}
}
else{
score[i] = score[i]^score[9-i];
score[9-i] = score[i]^score[9-i];
score[i] = score[i]^score[9-i];
}
}
for( int s : score){
System.out.println(s);
}
}
}这个也可能实现换位置。
作者:
打工人
时间:
2013-4-12 23:12
如果问题未解决,请继续追问,如果没有问题了,请将帖子分类 改为“已解决”,谢谢
作者:
zhangx
时间:
2013-4-13 10:54
嗯 看到了 解决了,谢谢你们
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2