66 lines
1.3 KiB
Java
66 lines
1.3 KiB
Java
package LanQiaoOJ;
|
||
/*含2天数
|
||
* 题目描述
|
||
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
|
||
小蓝特别喜欢 2,今年是公元 2020年,他特别高兴,因为每天日历上都可以看到 2。
|
||
如果日历中只显示年月日,请问从公元 1900 年 1 月1 日到公元 9999 年 12 月 31 日,一共有多少天日历上包含
|
||
2。即有多少天中年月日的数位中包含数字 2。
|
||
*/
|
||
public class 含2天数 {
|
||
//代表月份天数,从下标为1开始
|
||
static int[] w= {0,31,28,31,30,31,30,31,31,30,31,30,31};
|
||
//代表年月日
|
||
static int y=1900,m=1,d=1;
|
||
|
||
public static void main(String[] args) {
|
||
int count=0; //统计含2天数
|
||
//循环结束条件为y=9999&&m=12&&d=31
|
||
while(y!=9999||m!=12||d!=31) {
|
||
//判断是否为闰年
|
||
if(y%400==0||y%4==0&&y%100!=0)
|
||
w[2]=29;
|
||
else
|
||
w[2]=28;
|
||
//判断是否是我们要求的日期
|
||
if(check())
|
||
count++;
|
||
//日期变更
|
||
d++;
|
||
if(d>w[m]) {
|
||
m++;
|
||
d=1;
|
||
}
|
||
if(m>12) {
|
||
y++;
|
||
m=1;
|
||
}
|
||
}
|
||
System.out.println(count+1);
|
||
}
|
||
|
||
static boolean check() {
|
||
// TODO Auto-generated method stub
|
||
//不能直接操作y,因为其是一个全局变量
|
||
int a=y;
|
||
while(a>0) {
|
||
if(a%10==2)
|
||
return true;
|
||
a/=10;
|
||
}
|
||
int b=m;
|
||
while(b>0) {
|
||
if(b%10==2)
|
||
return true;
|
||
b/=10;
|
||
}
|
||
int c=d;
|
||
while(c>0) {
|
||
if(c%10==2)
|
||
return true;
|
||
c/=10;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
}
|