标签:
描述:    给定两个合法的时间(格式固定:hh:mm:ss,时间合法,不用考虑其它情况),输入两个时间相加后的结果;注意,相加后的结果也必需是一个合法的时间;
附合法时间定义:小时在[00-23]之间,分钟和秒分别是在[00-59]之间;
运行时间限制:    无限制
内存限制:    无限制
输入:    时分秒格式的时间字符串,如00:00:00
输出:    时分秒格式的时间字符串,如00:00:00
样例输入:    00:00:00 00:00:01
样例输出:    00:00:01
答案提示:    建议将时间转换为秒数计算
//定义一个时间结构
typedef struct
{
	  int hh, mm, ss;
}Time;
int testTime(Time *t)
{
  if (t->hh>23 || t->hh<0 || t->mm>59 || t->mm<0 || t->ss>59 || t->ss<0)
	  {
		    if (t->hh==24)
		    {
			      if (t->mm==0 || t->ss==0)
			      {
				        return 0;
			      }			
		    }
		    return -1;
	   }else 
		  return 0;
}
void addTime(Time t1, Time t2, Time *output)
{
	  int time1 = t1.hh*60*60 +t1.mm*60 +t1.ss;
	  int time2 = t2.hh*60*60 +t2.mm*60 +t2.ss;
	  int time = time1+time2;
	  double result;
	  Time* resultTime = (Time *)malloc(sizeof(Time));
	  resultTime->hh = time / (60*60);
	  time %= (60*60);
	  resultTime->mm = time / 60;
	  time %= 60;
	  resultTime->ss = time;
	  result = testTime(resultTime);
	  if(result == -1)
	  {
		    resultTime->hh -= 24;		
	  }
	  output->hh = resultTime->hh;
	  output->mm = resultTime->mm;
	  output->ss = resultTime->ss;		
}
int charToInt(char *ch){
    int len = strlen(ch);
    int k =10;
    int sum = 0;
    for(int i = 0;  i < len ; ++i){
        sum = sum * k + (ch[i] - ‘0‘);
    }
    return sum;
}
int countM(char* ch){
    int len = strlen(ch);
    int count =0;
    int k = 0;
    int sum =0;
    char b[3][3];
    for(int i = 0; i < len ; ++i){
        if(ch[i] <= ‘9‘ && ch[i] >= ‘0‘ ){
            b[count][k] = ch[i];
            k++;
        }else{
            b[count][k] = ‘\0‘;
            ++count;
            k = 0;
        }
    }
    b[count][k] = ‘\0‘;
    sum =  charToInt(b[0]) * 60 * 60 + charToInt(b[1]) * 60 + charToInt(b[2]);
    delete b;
    return sum;
}
int main(){
    char* ch1 = "23:12:56";
    char* ch2 = "23:12:56";
    //countM(ch);
    int number1 = countM(ch1);
    int number2 = countM(ch2);
    int sum = number1 + number2;
    int h = 0 , m = 0, s = 0;
    s = sum % 60;
    m = (sum / 60) % 60;
    h = (sum / 60 /60)%24 % 60;
    char ch[255];
    if(h < 10){
        cout<<"0"<<h;
    }else{
        cout<<h;
    }
    cout<<":";
    if(m < 10){
        cout<<"0"<<m;
    }else{
        cout<<m;
    }
    cout<<":";
    if(s < 10){
        cout<<"0"<<s;
    }else{
        cout<<s;
    }
    cout<<endl;
    return 0;
}
标签:
原文地址:http://www.cnblogs.com/shih/p/4624348.html