蓝桥杯-特殊日期

 修改了下某个大佬放的优雅代码

public class Main {
    public static void main(String[] args) {
        int count=0;
        int i,j,year,month;
        int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        for(year=1900;year<=9999;year++){
            if(year%4==0&&year%100!=0||year%400==0)
                days[2]=29;
            else
                days[2]=28;
            for(i=1;i<=12;i++){
                for(j=1;j<=days[i];j++){
                    if(fun(year)==fun(i)+fun(j))count++;
                }
            }
        }
        System.out.println(count);
    }

    static int fun(int n){
        int sum=0;
        while(n>0){
            sum+=n%10;
            n/=10;
        }
        return sum;
    }
}

对比一下自己写的垃圾代码

import java.util.Scanner;  
  
public class Main {  
    public static void main(String[] args) {  
        Scanner scan = new Scanner(System.in);  
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  
        int[] rdays = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  
        //是闰年直接修改二月份天数及days[1],不用在创建一个
        int count = 0;  
        int year = 1900, month = 1, day = 1;  
  
        while (year < 9999 || (year == 9999 && month < 12) || (year == 9999 && month == 12 && day <= 31)) {  
            // 判断是否是闰年  
            boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;  
            int[] currentDays = isLeapYear ? rdays : days;  
            //日期的改变可以直接采用for循环套用
            // 检查日期是否有效  
            if (day > currentDays[month - 1]) {  
                day = 1;  
                month++;  
                if (month > 12) {  
                    month = 1;  
                    year++;  
                }  
            } else {  
                // 检查年份的数位数字之和是否等于月的数位数字之和加日的数位数字之和  
                if (add(year) == add(month) + add(day)) {  
                    count++;  
                }  
                day++; // 在日期有效的情况下递增day  
            }  
        }  
  
        scan.close();  
        System.out.println(count);  
    }  
  
    public static int add(int num) {  
        int sum = 0;  
        while (num > 0) {  
            sum += num % 10;  
            num /= 10;  
        }  
        return sum;  
    }  
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值