知識點
處理日期
1. 按天枚舉日期:逐天遍歷起始日期到結束日期范圍內的每個日期。
2. 處理閏年:正確判斷閏年條件。閏年定義為:年份 滿足以下任意一個條件:(閏年的2月只有29天)
滿足下面一個條件就是閏年
1> 是 400 的倍數。
2> 是 4的倍數但不是 100的倍數
藝術與籃球
已知當前是星期幾求出某個月的某一天是星期幾
int week=x;x為第一天的日期
week = week%7+1求出每個星期的下一天
題目鏈接
1.藝術與籃球 - 藍橋云課
題目解析
判斷筆畫數是不是超過50,超過50就去練習書法
算法原理
使用哈希表,把筆畫和對應的數字聯系在一起
使用日期函數來標記時間的開始和結尾,然后遍歷每一天去計算筆畫數
代碼編寫
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;public class Main {public static void main(String[] args) {Map<Character, Integer> map = new HashMap<Character, Integer>() {{put('0', 13); // 零put('1', 1); // 一put('2', 2); // 二put('3', 3); // 三put('4', 5); // 四put('5', 4); // 五put('6', 4); // 六put('7', 2); // 七put('8', 2); // 八put('9', 2); // 九}};LocalDate startDate = LocalDate.of(2000, 1, 1);LocalDate endDate = LocalDate.of(2024, 4, 14);int days = 0;while (startDate.isBefore(endDate)) {String s = startDate.toString().replace("-", "");int total = 0;// 通過map查詢筆畫數for (char c : s.toCharArray()) {total += map.get(c);}if (total > 50) {days++;}startDate = startDate.plusDays(1);}System.out.println(days);}
}
從哪開始從哪結束
LocalDate startDate = LocalDate.of(2000, 1, 1);
LocalDate endDate = LocalDate.of(2024, 4, 14);
while
循環會一直執行,直到 startDate
等于或超過 endDate
。循環會逐日增加 startDate
,并計算當天日期的數字筆畫數。
startDate.isBefore(endDate)
轉為Srting類型,并且去除-
?startDate.toString().replace("-", "");
自增天數
? startDate = startDate.plusDays(1);
補充: 獲得xxx年xxx月xx日是星期幾
可以使用
LocalDate date = LocalDate.of(2026, 4, 1); // 獲取星期幾(英文)
String weekday = date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
另一種寫法
//造一個hash表,里面對應筆畫數int[] hash = {13, 1, 2, 3, 5, 4, 4, 2, 2, 2};//month里面放每月的個數int[] months = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//計算打籃球的天數int count = 0;boolean feb = true;for (int year = 2000; year <= 2024; year++) {//筆畫數int num = 0;//判斷是平年還是潤年//計算2月的值months[2] = isLeapYear(year) ? 29 : 28;//計算每一月,每一天for (int month = 1; month <= 12; month++) {for (int day = 1; day < months[month]; day++) {//計算年的每一位int ypos1 = year / 1000;year = year % 1000;int ypos2 = year / 100;year = year % 100;int ypos3 = year / 10;year = year % 10;int ypos4 = year;//計算月的每一位int mpos1 = month / 10;month = month % 10;int mpos2 = month;//計算每一天的每一位int dpos1 = day / 10;day = day % 10;int dpos2 = day;//計算筆畫數num = hash[ypos1] + hash[ypos2] + hash[ypos3] + hash[ypos4] +hash[mpos1] + hash[mpos2] + hash[dpos1] + hash[dpos2];//最后計算天數if (num > 50) {count++;}if (year == 2024 && month == 4 && day == 13) {System.out.println(count);return;}}}}}public static void main(String[] args) {cal();}