Time Zone

Time Zone

Problem Description

Chiaki often participates in international competitive programming contests. The time zone becomes a big problem.
Given a time in Beijing time (UTC +8), Chiaki would like to know the time in another time zone s.

Input

There are multiple test cases. The first line of input contains an integer T (1≤T≤106), indicating the number of test cases. For each test case:
The first line contains two integers a, b (0≤a≤23,0≤b≤59) and a string s in the format of “UTC+X”, “UTC-X”, “UTC+X.Y”, or “UTC-X.Y” (0≤X,X.Y≤14,0≤Y≤9).

Output

For each test, output the time in the format of hh:mm (24-hour clock).

Sample Input

3
11 11 UTC+8
11 12 UTC+9
11 23 UTC+0

Sample Output

11:11
12:12
03:23

題目概述

時區

問題描述

Chiaki經常參加國際競爭性編程競賽。時區成了一個大問題。

給定一個北京時間(UTC +8), Chiaki想知道另一個時區的時間。

輸入

有多個測試用例。輸入的第一行包含一個整數T(1≤T≤106),顯示測試用例的數量。爲每個測試用例:

第一行包含兩個整數a、b b(0≤≤23日0≤≤59)和一個字符串格式的“UTC + X”,“UTC-X”、“UTC + X..Y”,或“UTC-X.Y”(0≤X,X.Y≤14 0≤Y≤9)。

輸出

每次測試輸出的時間格式爲hh:mm(24小時時鐘)。

樣例輸入

3

11 11 UTC + 8
11 12 UTC + 9
11 23 UTC + 0

樣例輸出

11:11
12:12
03:23

解題思路

根據題目意思與測試樣例我們可以看出
當輸入的 是“+”,即 UTC + n 時,需要比較n與8的大小(因爲北京是UTC + 8)
如果n<8則讓8-n ,此時將輸入的時間 -(8-n)
如果n>8則讓n-8 ,此時將輸入的時間 +(n-8)
(我們不妨直接用輸入的時間+n-8
當輸入的 是“-”,即 UTC - n 時,不需要比較n與8的大小(因爲負數一定比8小)
此時我們將輸入的時間 -8-n即可

最後判斷變型後的小時和分鐘是否符合規定格式
設小時數值爲h 分鐘數值爲 s
當 h>24 時 h=h-24
當 h<0 時 h=24+h
當 s>60 時 s=s-60且h++
當 s<60 時 s=60+s且h- -

代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int n,h,m;
    double s;
    char fu[20];
    scanf("%d",&n); 
    while(n--)
    {
        scanf("%d %d ",&h,&m);
        scanf("%s",fu);       //輸入UTC -/+ n
        sscanf(fu+4,"%lf",&s);//此處用到sscanf進行轉化(字符轉化爲浮點數)
        int newh,newm;
        newh=s/1;             //得到n中的小時數
        if(fu[3]=='+')
        {
            h+=(newh-8);     //將小時數轉化爲北京時間
            newm=(s-newh)*60+0.01; //得到n中的分鐘數
 //加一個0.01是因爲存在精度問題 例如輸入的n=10.2 但是轉換爲浮點數後爲10.19999
            m+=newm;         //將分鐘數轉化爲北京時間
        }
        else
        {
            h=h-newh-8;
            newm=(s-newh)*60+0.01; //同上
            m-=newm;
        }
         if(m>=60)  //判斷得到的北京時間是否符合題意
            {
                m-=60;
                h++;
            }
        if(h>=24)
            {
                h-=24;
            }
        if(m<0)
            {
                m+=60;
                h--;
            }
        if(h<0)
            {
                h+=24;
            }
        printf("%02d:%02d\n",h,m); //保留兩位不足兩位自動向前補0
    }
    return 0;
}

各位親不懂的地方歡迎留言 留個讚唄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章