gpt4 book ai didi

Java,计算从1901年到2000年每个月的第一个星期天的数量

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:35 26 4
gpt4 key购买 nike

我是编程和 Java 的新手,我正在尝试通过 Project Euler 网站自学。我正在尝试解决这个问题:http://projecteuler.net/problem=19 ,即:

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

我想解决这个问题的方法是制作一个代表压延机的二维数组,然后通过数到 7 遍历数组,然后每次我数到 7 时,将数组中的那个点加 1 .最后,我会对数组的第一行求和,这应该是一个月的第一天有多少个星期日。

但是我的循环有问题,当它到达月底时我的计数会重置为 7,我不知道如何阻止它这样做?

这是我的代码:

public class Problem019 {
public static void main (String[] args){

//System.out.println(LeapYearTest(1996));
int ThirtyOne = 31;
int Thirty = 30;
int FebNorm = 28;
int FebLeap = 29;
int a, b, c, Day, e = 0, f = 0;
int Calander[] []= new int [12] [] ;

Calander[0] = new int [ThirtyOne];
Calander[1] = new int [FebNorm];
Calander[2] = new int [ThirtyOne];
Calander[3] = new int [Thirty];
Calander[4] = new int [ThirtyOne];
Calander[5] = new int [Thirty];
Calander[6] = new int [ThirtyOne];
Calander[7] = new int [ThirtyOne];
Calander[8] = new int [Thirty];
Calander[9] = new int [ThirtyOne];
Calander[10] = new int [Thirty];
Calander[11] = new int [ThirtyOne];

for (a=1901;a<2001;a++){
//System.out.println(a);
if (LeapYearTest(a))
{
Calander[1] = new int [FebLeap];
}
else
{
Calander[1] = new int [FebNorm];
}

for (e=0;e<Calander.length;e++)
{
System.out.println("e: " + e);
f=0;

while (f<Calander[e].length)
{

//System.out.println(Calander[e].length);
Day=1;
while (Day<8 && f<Calander[e].length)
{
System.out.println("f: " + f + "\tDay: " + Day + "\tCalander[e][f]: " + Calander[e][f]);
Day++;
f++;

if (f<Calander[e].length && f!=0 && Day==7)
{
Calander[e][f]+= 1;
}

}

}
}
//System.out.println(a);
}
for (b=0;b<Calander.length;b++)
{
System.out.print(Calander[0][b]);
}
}


public static boolean LeapYearTest(int x)
{
if (x%4==0 || x%400==0){
return true;
}
if (x%100==0){
return false;
}
else return false;
}

}

这是它打印的内容,e 是月份,f 是月份中的天数,Day 数到 7:

f: 25   Day: 5  Calander[e][f]: 0
f: 26 Day: 6 Calander[e][f]: 0
f: 27 Day: 7 Calander[e][f]: 100
f: 28 Day: 1 Calander[e][f]: 0
f: 29 Day: 2 Calander[e][f]: 0
**f: 30 Day: 3 Calander[e][f]: 0**
e: 10
**f: 0 Day: 1 Calander[e][f]: 0**
f: 1 Day: 2 Calander[e][f]: 0
f: 2 Day: 3 Calander[e][f]: 0

如何设置循环,使 Day 不会在月底重置?或者有没有另一种方法可以解决这个问题而不涉及那么多嵌套循环?

谢谢!

最佳答案

如果有一个外部循环将年份从 1901 递增到 2001 年,内部循环检查一月 -> 十二月,然后只查看该月的第一天是否是星期日,会不会更快?

总共100 * 12次迭代,10行代码,tops。

编辑:对此进行扩展。

您可以通过两种方式解决这个问题 - 查看所有星期日,看看它们是否在一个月的第一天,或者查看所有月份的第一天,看看它是否是星期日。

未经测试的代码:

Calendar calendar = Calendar.getInstance();
int count = 0;
for(int i=1901;i<2000;i++){
for(int j=1;i<12;j++){
calendar.set(Calendar.YEAR, i);
calendar.set(Calendar.MONTH,j);
calendar.set(Calendar.DAY,1);
if(calendar.get(Calendar.DAY_OF_WEEK).equals(Calendar.SUNDAY)){
count++;
}
}
}

System.out.println(count);

关于Java,计算从1901年到2000年每个月的第一个星期天的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10370508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com