极客之年
2001 年 1 月 1 日是星期一。如果这一年的 1 月 1 日恰好是星期日,我们就称这一年为 Geeky。将有两年' a '和' b '。任务是找到没有。这两年之间的 Geeky 年份(包括“a”和“b”)
例子:
Input: a = 2001, b = 2013
Output: 2
Input: a = 2020, b = 2024
Output: 1
方法:这个想法是存储每个月的天数,然后计算答案。请按照以下步骤解决问题:
- 将变量count初始化为0 。
- 使用变量i遍历范围[a, b]并执行以下任务:
- 将变量y初始化为i-1。
- 将变量ans初始化为(y + y / 4 – y / 100 + y / 400) % 7。
- 如果ans等于6 ,则将count的值增加 1。
- 执行上述步骤后,打印count的值作为答案。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count the total number
// of years
int Count(int a, int b)
{
// Days shifts for each month
int t[] = { 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 };
// Store the answer
int count = 0;
// Traverse over the years
for (int i = a; i <= b; i++) {
int y = i - 1;
int ans = (y + y / 4 - y / 100 + y / 400) % 7;
if (ans == 6) {
count++;
}
}
return count;
}
// Driver Code
int main()
{
int a = 2001;
int b = 2013;
int ans = Count(a, b);
cout << ans;
}
// This code is contributed by Samim Hossain Mondal.
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to count the total number
// of years
public static int Count(int a, int b)
{
// Days shifts for each month
int t[] = { 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 };
// Store the answer
int count = 0;
// Traverse over the years
for (int i = a; i <= b; i++) {
int y = i - 1;
int ans = (y + y / 4
- y / 100 + y / 400)
% 7;
if (ans == 6) {
count++;
}
}
return count;
}
// Driver Code
public static void main(String[] args)
{
int a = 2001;
int b = 2013;
int ans = Count(a, b);
System.out.println(ans);
}
}
Python3
# Python 3 program for the above approach
# Function to count the total number
# of years
def Count(a, b):
# Days shifts for each month
t = [0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4]
# Store the answer
count = 0
# Traverse over the years
for i in range(a, b + 1):
y = i - 1
ans = (y + y // 4 - y // 100 + y // 400) % 7
if (ans == 6):
count += 1
return count
# Driver Code
if __name__ == "__main__":
a = 2001
b = 2013
ans = Count(a, b)
print(ans)
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
class GFG {
// Function to count the total number
// of years
public static int Count(int a, int b)
{
// Days shifts for each month
int []t = { 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 };
// Store the answer
int count = 0;
// Traverse over the years
for (int i = a; i <= b; i++) {
int y = i - 1;
int ans = (y + y / 4
- y / 100 + y / 400)
% 7;
if (ans == 6) {
count++;
}
}
return count;
}
// Driver Code
public static void Main()
{
int a = 2001;
int b = 2013;
int ans = Count(a, b);
Console.WriteLine(ans);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
2
时间复杂度: O(N)
辅助空间: O(1)