今天我想最小化的最后一件事是包含 while 和 do-while 循环的代码。原文如下:
class Vereinfache3_edit {
public static void main(String [] args) {
int c1 = Integer.parseInt(args[0]) ;
int c2 = Integer.parseInt(args[1]) ;
int c3 = Integer.parseInt(args[2]) ;
/* 1 */ c1 += 7 ;
/* 2 */ System.out.println( c1 ) ;
/* 3 */ while (c1 % 8 != 0)
/* 4 */ if ( c1 % 16 == 0 ) ;
/* 5 */ else
/* 6 */ do
/* 7 */ {
/* 8 */ c1 += 7 ;
/* 9 */ System.out.println( c1 ) ;
/* 10 */ if ( c2 < c3 )
/* 11 */ { c1 = c1+c1 ;
/* 12 */ c3 ++ ;
/* 13 */ c1 /= 2 ;
/* 14 */ c3 -= 1 ;
/* 15 */ }
/* 16 */ }
/* 17 */ while ( c1 % 8 != 0 ) ;
/* 18 */ c1 += 7 ;
/* 19 */ System.out.println( c1 ) ;
}
} // end of class Vereinfache3
这是我的最小化版本:
class Vereinfache3 {
public static void main(String [] args) {
int c1 = Integer.parseInt(args[0]);
int c2 = Integer.parseInt(args[1]) ;
int c3 = Integer.parseInt(args[2]) ;
do{
c1 += 7 ;
System.out.println( c1 ) ;
}while (c1 % 8 != 0);
/* 18 */ c1 += 7 ;
/* 19 */ System.out.println( c1 ) ;
}
} // end of class Vereinfache3
它为我生成相同的输出。您是否发现任何错误或可以改进的地方?
尤其是这段代码似乎很棘手:
/* 3 */ while (c1 % 8 != 0)
/* 4 */ if ( c1 % 16 == 0 ) ;
/* 5 */ else
/* 6 */ do{}
我该如何处理这段时间? while 循环包含什么?
最佳答案
您的最小化版本产生与原始版本相同的结果,原始解决方案和最小化版本的不同输出仅在 c1 % 8 != 0 and c1 % 16 == 0
的情况下才可能发生。 ,
这种情况是不可能的,因为 16 的所有倍数也是 8 的倍数..
删除未使用的声明..是我可以建议的唯一改进。 我确实有一个代码更少的解决方案..并不是说它使事情变得更好...我不喜欢代码中有太多系统输出..:)
int finalBound = ((c1 + 7) % 8 == 0) ? c1 + 7 : 8 * c1;
for (; c1 <= finalBound; c1 += 7) {
System.out.println(c1 + 7);
}
希望有帮助。
关于java - 最大限度地减少读/写操作的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062970/