在C ++中查找下一个相同的日历年
假设我们有一个年份Y。找到下一个与Y相同的日历年。因此2017年的日历与2023年相同。
如果X符合这两个条件,则它与给定的上一年Y相同。
x从年份的同一天开始,
如果y是leap年,则x也是,如果y是正常年,则x也是正常年。
这个想法是从明年开始逐年检查所有年份。我们将跟踪前进的天数。如果总共移动了7天,则当前年份从同一天开始。我们还检查当前年份是否为leap年,如果是,则还要检查y。如果两个条件都满足,我们将返回当前年份。
示例
#include<iostream>
using namespace std;
int countExtraDays(int y) {
if (y%400==0 || y%100!=0 && y%4==0)
return 2;
return 1;
}
int nextIdenticalYear(int y) {
int days = countExtraDays(y);
int x = y + 1;
for (int sum=0; ; x++) {
sum = (sum + countExtraDays(x)) % 7;
if ( sum==0 && (countExtraDays(x) == days))
return x;
}
return x;
}
int main() {
int curr = 2019;
cout << "Next identical year of " << curr <<" is: " << nextIdenticalYear(curr);
}输出结果
Next identical year of 2019 is: 2030
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短