模板:
1、months数组:int month[13]:0,31,28,31,30,31,30,31,31,30,31,30,31
2、判断是否闰年:返回int,方便计算天数
int isLeap(int year){
if(year%4==0&&year%100!=0||year%400==0)return 1;
return 0;
}
3、返回某年某月的天数:
int getDays(int year,int month){
int res=0;
res+=months[month];
if(month==2)res+=isLeap(year);
return res;
}
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
题意:给定YYYY-MM-DD,返回一年中的第几天。
class Solution {
public final int[] months={
0,31,28,31,30,31,30,31,31,30,31,30,31
};
private int isLeap(int year){
if(year%4==0&&year%100!=0||year%400==0)return 1;
else return 0;
}
int getDays(int year,int month){
int res=months[month];
if(month==2)res+=isLeap(year);
return res;
}
public int dayOfYear(String date) {
int year=Integer.parseInt(date.substring(0,4));
int month=Integer.parseInt(date.substring(5,7));
int day=Integer.parseInt(date.substring(8));
int res=0;
for(int i=1;i<=month-1;i++){
res+=getDays(year,i);
}
res+=day;
return res;
}
}
给定年月日, 求这一天星期几。
其中年在1971~2100。
求当天距离1970最后一天有多少天,然后模7即可。
class Solution {
public final int[] months={
0,31,28,31,30,31,30,31,31,30,31,30,31
};
private int isLeap(int year){
if(year%4==0&&year%100!=0||year%400==0)return 1;
else return 0;
}
int getDays(int year,int month){
int res=months[month];
if(month==2)res+=isLeap(year);
return res;
}
public String dayOfTheWeek(int day, int month, int year) {
String[] week={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
int res=4;
for(int i=1971;i<year;i++){
res+=365+isLeap(i);
}
for(int i=1;i<month;i++){
res+=getDays(year,i);
}
res=(res+day%7)%7;
return week[res];
}
}