算法设计与编程 当天的第几秒 题型:时间日期类题 简单

74 阅读1分钟

赛氪OJ-专注于算法竞赛的在线评测系统 (saikr.com)

我刚开始是这样想的:

从0:0:0到12点:59:59是上午

从1:0:0到11:59:59是下午

题目下午一点不会输入:13点,而是输入 1点 P

那么我们就应该把前面缺的那个12个小时加上,就变成了13.

初始代码

#include<bits/stdc++.h>
using namespace std;
int h,m,s;
char c;
int Time; 


int main()
{
	cin>>h>>m>>s>>c;
	
	//从0:0:0到12点:59:59是上午
	//从1:0:0到11:59:59是下午
	
//	cout<<"h:m:s: "<<h<<" "<<m<<" "<<s<<endl;
	if(c=='A') //上午 
	{
		Time=h*60*60+m*60+s;
	}
	else  //下午 
	{
	
		Time=h*60*60+m*60+s;
    Time*=2;
	} 
	
	
	cout<<Time<<endl;
	return 0;
}

第二个例子和答案差1秒:

image.png

优化代码

后来先把时间加上12,就过了:

#include<bits/stdc++.h>
using namespace std;
int h,m,s;
char c;
int Time; 


int main()
{
	cin>>h>>m>>s>>c;
	
	//从0:0:0到12点:59:59是上午
	//从1:0:0到11:59:59是下午
	
//	cout<<"h:m:s: "<<h<<" "<<m<<" "<<s<<endl;
	if(c=='A') //上午 
	{
		Time=h*60*60+m*60+s;
	}
	else  //下午 
	{
		h+=12;
		Time=h*60*60+m*60+s;
	} 
	
	
	cout<<Time<<endl;
	return 0;
}

image.png