算法刷题记录:日历中的数字

发布时间 2023-06-02 14:16:15作者: 想个昵称好难ABCD

题目链接

https://ac.nowcoder.com/acm/contest/19859/B

题目分析

很简单的一道数位统计的题目

  • 其中年和月是乘法原理。(固定住年和月,枚举该月有几天,所以是乘法原理)
  • x=0并且month<10时,月需要特判一位数的情况,是加法原理
  • 日是加法原理

AC代码

// Problem: 日历中的数字
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/19859/B
// Memory Limit: 262144 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>

using namespace std;

int y, m, x;
int day[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int get_month_day(int year, int mon)
{
	int res = day[mon];
	if (mon == 2 && ((!(year % 4) && year % 100) || !(year % 400)))
		res += 1;
	return res;
}

// 1.判断年的所有情况 -> 乘法原理(要选的数字出现在年中)
// 2.判断月的所有情况 -> 乘法原理(要选的数字出现在月中)
// 3.判断日的所哟情况 -> 加法原理,数字中是否存在
int main()
{
	while (cin >> y >> m >> x)
	{
		// 处理年
		int t = y, ycnt = 0;
		while (t)
		{
			if (t % 10 == x) ycnt ++ ;
			t /= 10;
		}
		
		int day = get_month_day(y, m);
		ycnt *= day, t = m;
		// if (y == 2000) cout << day << endl;
		// 处理月,月有前导0(一位数特判)
		int mcnt = 0;
		while (t)
		{
			if (t % 10 == x) mcnt ++ ;
			t /= 10; 
		}
		mcnt *= day;
		if (!x && m < 10) mcnt += day;
		
		
		// 处理月
		int dcnt = 0;
		for (int i = 1; i <= day; ++ i)
		{
			int tmp = i;
			while (tmp) 
			{
				if (tmp % 10 == x) dcnt ++ ;
				tmp /= 10;
			}
		}
		if (!x) dcnt += 9;
		
		cout << ycnt + mcnt + dcnt << endl;
	}
}