提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
俩到经典题目
一、计算日期到天数的转换
题目描述
解题分析
代码演示
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));
}
}