P5711 闰年判断
对应章节:三、解题方法论:从题意到代码 → (五) 从文字规则整理优先级。
(一) 任务与输出目标
根据公历规则判断年份是否为闰年。
(二) 建模与推导
年份能被 400 整除时是闰年;否则,能被 4 整除且不能被 100 整除时是闰年。把第二条中的“且”写成 &&,再用 || 合并两种成立方式。
(三) 手算与过程
1900 被 100 整除而不被 400 整除,输出 0;2000 被 400 整除,输出 1。
(四) 带注释实现
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
void solve() {
int year;
cin >> year;
bool leap = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
cout << leap << '\n'; // bool 输出 1 或 0,对应题目要求。
}
signed main() {
ios::sync_with_stdio(false); // 关闭同步,使用 cin 与 cout 完成输入输出。
cin.tie(0), cout.tie(0);
int T = 1; // 本题读入一组数据。
// cin >> T; // 题目给出测试组数时开启,并在 solve 中处理一组。
while (T--)
solve();
}(五) 复杂度
时间 \(O(1)\),额外空间 \(O(1)\)。