英文:
I want to calculate the last 20 leap year for which I have written this code, can this code be further optimized
问题
package javaHM;
import java.util.*;
public class LeapYear {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter Starting Year");
int year = obj.nextInt();
obj.close();
leapFor(year);
}
public static void leapFor(int year) {
int counter = 0;
for (int i = year; counter < 20; i--) {
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
System.out.println(i);
counter++;
}
}
}
}
英文:
package javaHM;
import java.util.*;
public class LeapYear {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner obj = new Scanner(System.in);
System.out.println("Enter Starting Year");
int year = obj.nextInt();
leapFor(year);
obj.close();
}
public static int leapFor(int year) {
int counter = 0, i;
for (i = year; i >= 1; i--) {
if ((i % 4 == 0) && i % 100 != 0 || i % 400 == 0) {
System.out.println(i);
counter++;
}
if (counter == 20)
break;
}
return i;
}
}
I want to optimize this portion of code , please help me
答案1
得分: 0
您的函数在每次迭代中执行I/O操作。I/O操作速度较慢,因此具有最大影响的优化是将输出累积到缓冲区中,然后仅在最后一次打印。对算法的任何更改都不会产生有意义的差异。
public static int leapFor(int year) {
int counter = 0, i;
StringBuilder output = new StringBuilder(20*(4+1));
for (i = year; i >= 1; i--) {
if ((i % 4 == 0) && i % 100 != 0 || i % 400 == 0) {
output.append(i).append('\n');
counter++;
}
if (counter == 20)
break;
}
System.out.print(output);
return i;
}
英文:
Your function does I/O on every iteration. I/O is slow, so the optimization with the biggest effect is accumulating the output into a buffer, and printing it only once. Any changes to the arithmetic will not make a meaningful difference.
public static int leapFor(int year) {
int counter = 0, i;
StringBuilder output = new StringBuilder(20*(4+1));
for (i = year; i >= 1; i--) {
if ((i % 4 == 0) && i % 100 != 0 || i % 400 == 0) {
output.append(i).append('\n');
counter++;
}
if (counter == 20)
break;
}
System.out.print(output);
return i;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论