练习题——【学习补档】计算日期到天数转换

问题描述

根据输入的日期,计算是这一年的第几天。

保证年份为4位数且日期合法。

进阶:时间复杂度:O(n) ,

空间复杂度:O(1)

输入描述:

输入一行,每行空格分割,分别是年,月,日

输出描述:

输出是这一年的第几天
示例1

输入:

2012 12 31

输出:

366
示例2

输入:

1982 3 4

输出:

63

问题分析

该问题就是数天数。😁

解决方案

我们只需要算出输入的日期距年初总共多少天即可。

代码

c 复制代码
#include <iostream>
using namespace std;

int GetMonthDay(int year, int month)
{
	const static int day_arr[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (month == 2
		&& (year % 4 == 0 && year % 100 != 0 || (year % 400 == 0)))
	{
		return 29;
	}
	return day_arr[month];
}

int main()
{
	int year, month, day;
	cin >> year >> month >> day;
	while (month != 1)
	{
		day += GetMonthDay(year, month - 1);
		month--;
	}
	cout << day;
}
相关推荐
匆匆那年9674 小时前
llamafactory推理消除模型的随机性
linux·服务器·学习·ubuntu
好好学习天天向上~~4 小时前
5_Linux学习总结_vim
linux·学习·vim
笨笨阿库娅4 小时前
从零开始的算法基础学习
学习·算法
阿蒙Amon12 小时前
TypeScript学习-第10章:模块与命名空间
学习·ubuntu·typescript
AI绘画哇哒哒13 小时前
【干货收藏】深度解析AI Agent框架:设计原理+主流选型+项目实操,一站式学习指南
人工智能·学习·ai·程序员·大模型·产品经理·转行
戌中横13 小时前
JavaScript——预解析
前端·javascript·学习
●VON14 小时前
React Native for OpenHarmony:2048 小游戏的开发与跨平台适配实践
javascript·学习·react native·react.js·von
ZH154558913114 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh14 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh14 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics