如何递归地干燥这段代码以避免重复该月的日期。
我有一个想法,为一月设置一个基本情况,并通过递归计算上个月的 dayOfYear 来处理其他月份,然后将当前月份添加到其中。
类似于 if (month == 1) { ... } else { ... dayOfYear(month-1, dayOfMonth,year) ... } 正确
但我不太确定具体的实现方式,也不知道这是否是一个准确的方法。
假设我有一个这样的数组,可以存储我所有的日子 int[] 月长度 = 新 int[] { 31, 28, 31, 30, ..., 31}
public static int dayOfYear(int month, int dayOfMonth, int year) {
if (month == 2) {
dayOfMonth += 31;
} else if (month == 3) {
dayOfMonth += 59;
} else if (month == 4) {
dayOfMonth += 90;
} else if (month == 5) {
dayOfMonth += 31 + 28 + 31 + 30;
} else if (month == 6) {
dayOfMonth += 31 + 28 + 31 + 30 + 31;
} else if (month == 7) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30;
} else if (month == 8) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30 + 31;
} else if (month == 9) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31;
} else if (month == 10) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30;
} else if (month == 11) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31;
} else if (month == 12) {
dayOfMonth += 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 31;
}
return dayOfMonth;
}
最佳答案
正如其他答案中所建议的,您可以轻松避免递归,只需用一年中第一天到每月第一天之间的天数填充数组即可。
因为从复杂性的角度来看,递归将需要 O(n)
和带有预定义数组的算法 - O(1)
但是如果你真的想使用递归,你可以在一些准备好的数组中填充天数,并使用月
作为数组的索引进行计算。
例如:
public static int[] daysOfMonth = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public int daysOfYear(int day, int month, int year) {
if (month == 0) {
return day;
}
//specific case for leap year
int leapOffset = 0;
if (month == 2) {
if (Year.of(year).isLeap()) {
leapOffset = 1;
}
}
return daysOfYear(day + daysOfMonth[month-1] + leapOffset, month - 1, year);
}
并测试:
@Test
public void testDay() {
Assert.assertEquals(LocalDate.of(2015, Month.FEBRUARY, 25).getDayOfYear(), daysOfYear(25, 1, 2015));
Assert.assertEquals(LocalDate.of(2014, Month.MARCH, 25).getDayOfYear(), daysOfYear(25, 2, 2014));
Assert.assertEquals(LocalDate.of(2013, Month.MAY, 25).getDayOfYear(), daysOfYear(25, 4, 2013));
Assert.assertEquals(LocalDate.of(2012, Month.JUNE, 25).getDayOfYear(), daysOfYear(25, 5, 2012));
}
关于java - 递归DRY代码,计算月份中的天数,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937343/