每日一题(day14) 计算日期到天数的转换 幸运的袋子

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

俩到经典题目


一、计算日期到天数的转换

题目描述

在这里插入图片描述

解题分析

在这里插入图片描述

代码演示

public static boolean is_run_year(int y) {
    if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
        return true;
    }
    return false;
}

public static int CountDay(int y, int m, int d) {
    int days = 0;
    int[] array = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (m >= 3 && is_run_year(y)) {
        days += 1;
    }
    try {
        for (int i = 1; i < m; i++) {
            days += array[i];
        }
    }catch (ArrayIndexOutOfBoundsException e){
        e.printStackTrace();
    }finally{
        System.out.println("请重新输入月份");
    }

    days += d;
    return days;
}

public static void main(String[] args) {
    //日期到天数的转换
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNext()) {
        int year = scanner.nextInt();
        int month = scanner.nextInt();
        int day = scanner.nextInt();
        int days = CountDay(year, month, day);
        System.out.println(days);
    }
}

二.幸运的袋子

题目描述

在这里插入图片描述

解题分析

回溯+递归
在这里插入图片描述

思路:
在这里插入图片描述
官方题解:
在这里插入图片描述

代码演示

 import java.util.Arrays;
import java.util.Scanner;
public class Main {
 public static int fun(int[]arr,int n,int pos,int sum,int mul){
        int count=0;
        for (int i = pos; i <n ; i++) {
            sum+=arr[i];
            mul*=arr[i];
            if(sum>mul){
                count=count+1+fun(arr,n,i+1,sum,mul);
            }else if(arr[i]==1){
                count=count+fun(arr,n,i+1,sum,mul);//1*任何数小于其和,要考虑后续是否还存在幸运的袋子
            }else{
                break;
            }
            //递归完毕,开始回溯
            sum-=arr[i];
            mul/=arr[i];
            while(i<n-1&&arr[i]==arr[i+1]){//避免产生俩个相同的幸运的袋子
                i++;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int []array=new int[n];
        for (int i = 0; i <n ; i++) {
            array[i]=scanner.nextInt();
        }
        Arrays.sort(array);
        System.out.println(fun(array,n,0,0,1));
    }
}

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值