Kotlin Language : How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Here is your solution:
fun sundaysInTwentCentury(): Int {
fun daysInMon(month: Int, year: Int) = when(month) {
1,3,5,7,8,10,12 -> 31
4,6,9,11 -> 30
2 -> when {
year % 400 == 0 -> 29
year % 100 == 0 -> 28
year % 4 == 0 -> 29
else -> 28
}
else -> throw Exception("Invalid Month ${month}")
}
fun daysInYears(year: Int): Int {
var days = 0
for(month in 1..12) {
days += daysInMon(month, year)
}
return days
}
fun dayOfWeekAfter(currentDow: Int, numberOfDays: Int) = ((currentDow-1) + numberOfDays) % 7 + 1
var weekDayOnFirstOfMonth = dayOfWeekAfter(2, daysInYears(1900))
var totalSundays = 0
for (year in 1901..2000) {
for(month in 1..12) {
if (weekDayOnFirstOfMonth == 1) totalSundays++
weekDayOnFirstOfMonth = dayOfWeekAfter(weekDayOnFirstOfMonth, daysInMon(month,year))
}
}
return totalSundays
}
Get Answers For Free
Most questions answered within 1 hours.