paiza練習問題 曜日[LARGE]をyoutube解説動画を視て書く。
ポイント
うるう年は400年周期で同じルールが適用されるので、400年の日数を計算する。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DayOfWeekLarge
{
class Program
{
static void Main(string[] args)
{
string[] input = Console.ReadLine().Trim().Split(' ');
long year = long.Parse(input[0]);
long month = long.Parse(input[1]);
long day = long.Parse(input[2]);
//1800年1月1日からの日数を計算する
long count = countDay(year, month, day);
string[] dayOfWeek = new string[] { "水", "木", "金", "土", "日", "月", "火" };
Console.WriteLine(dayOfWeek[count % 7] + "曜日");
}
//ある年月の最終日を返す
static long lastDay(long year,long month)
{
switch (month)
{
case 2:
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
{
return 29;
}
else
{
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
// 次の日を計算するメソッド
static long[] nextDay(long year, long month, long day)
{
day++;
if(day > lastDay(year,month))
{
day = 1;
month++;
}
if(month > 12)
{
month = 1;
year++;
}
return new long[] { year, month, day };
}
//1800年1月1日からの日数を計算するメソッド
static long countDay(long year,long month,long day)
{
long y = 1800, m = 1, d = 1;
long count = 0;
//400年分の日数を計算
long DaysOf400Years = 365 * 400 + (400 / 400) - (400 / 100) + (400 / 4);
//400の倍数年未来に飛ぶ
count += ((year - 1800) / 400) * DaysOf400Years;
y = year - (year - 1800) % 400;
while(!(y == year && m == month && d == day))
{
//一日ずつ進める
count++;
long[] tomoorow = nextDay(y, m, d);
y = tomoorow[0];
m = tomoorow[1];
d = tomoorow[2];
}
return count;
}
}
}