首页 > 试题广场 >

时钟

[编程题]时钟
  • 热度指数:11864 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
注意:本题允许使用C/C++/Java/python进行解答,其他编程语言提交均视作无效处理。

W有一个电子时钟用于显示时间,显示的格式为HH:MM:SSHHMMSS分别表示时,分,秒。其中时的范围为[‘00’,‘01’…‘23’],分的范围为[‘00’,‘01’…‘59’],秒的范围为[‘00’,‘01’…‘59’]

但是有一天小W发现钟表似乎坏了,显示了一个不可能存在的时间“98:23:00”,小W希望改变最少的数字,使得电子时钟显示的时间为一个真实存在的时间,譬如“98:23:00”通过修改第一个’9’’1’,即可成为一个真实存在的时间“18:23:00”。修改的方法可能有很多,小W想知道,在满足改变最少的数字的前提下,符合条件的字典序最小的时间是多少。其中字典序比较为用“HHMMSS”的6位字符串进行比较。


输入描述:
每个输入数据包含多个测试点。每个测试点后有一个空行。 第一行为测试点的个数T(T<=100)。 每个测试点包含1行,为一个字符串”HH:MM:SS”,表示钟表显示的时间。


输出描述:
对于每个测试点,输出一行。如果钟表显示的时间为真实存在的时间,则不做改动输出该时间,否则输出一个新的”HH:MM:SS”,表示修改最少的数字情况下,字典序最小的真实存在的时间。
示例1

输入

2
19:90:23
23:59:59

输出

19:00:23
23:59:59
#include<bits/stdc++.h>
using namespace std;
int main(){
    int T,H,M,S;
    scanf("%d", &T);
    while(T--){
        scanf("%d:%d:%d", &H, &M, &S);
        if(H>=24)
            H %= 10;
        if(M>=60)
            M %= 10;
        if(S>=60)
            S %= 10;
        printf("%02d:%02d:%02d\n", H, M, S);
    }
    return 0;
}

发表于 2019-07-15 09:13:16 回复(1)
""""
最小改动
"""

if __name__ == "__main__":
    n = int(input().strip())
    for _ in range(n):
        HH, MM, SS = map(int, input().strip().split(':'))
        if HH >= 24:
            HH %= 10
        if MM >= 60:
            MM %= 10
        if SS >= 60:
            SS %= 10
        print("{0:02d}:{1:02d}:{2:02d}".format(HH, MM, SS))

发表于 2019-07-12 14:24:09 回复(2)

1 思路分析

  1. 将输入字符串按照 ':'分割为三个字符串。
  2. 然后将三个字符串分别转换为 int 类型。
  3. 对时分秒对应的值分别处理,超出范围的就将十位改为0。

2 代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i < n; ++ i) {
            String input = scanner.next();
            String[] strs = input.split(":");

            int h = Integer.parseInt(strs[0]);
            if (h > 23) {
                strs[0] = "0" + strs[0].charAt(1);
            }

            int m = Integer.parseInt(strs[1]);
            if (m > 59) {
                strs[1] = "0" + strs[1].charAt(1);
            }

            int s = Integer.parseInt(strs[2]);
            if (s > 59) {
                strs[2] = "0" + strs[2].charAt(1);
            }

            System.out.println(strs[0] + ":" + strs[1] + ":" + strs[2]);
        }
    }
}
发表于 2019-11-21 09:41:50 回复(0)
//只要判断时分秒位是否大于23、59、59,如果大的话,就把高位置为零即可


#include <iostream>
#include <string>
using namespace std;
string check(string s){
    if(s.substr(0,2)>"23") s[0]='0';
    if(s.substr(3,2)>"59") s[3]='0';
    if(s.substr(6,2)>"59") s[6]='0';
    return s;
}
int main(){
    int N;
    cin>>N;
    while(N>0){
        string str;
        cin>>str;
        cout<<check(str)<<endl;
        N--;
    }
    return 0;
}

发表于 2019-07-24 19:12:42 回复(0)
只要小时大于23,分钟和秒大于59就把小时、分钟、秒的高位置为0,就能满足条件了吧,这样做不知道为什么通过率0%,求解答
发表于 2018-08-10 22:02:56 回复(18)
我的应该是最简洁的了吧嘻嘻!我愿称正则表达式之为绝配!!(我是受前面那个万万没想到编辑的题有所感发的!)直接上代码吧!求点赞!!!😁
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        sc.nextLine();
        for(int i=0;i<T;i++){
            System.out.println(
                sc.nextLine().replaceFirst("^[3-9]","0").replaceFirst("^2([4-9])","0$1")
                .replaceAll("[6-9](\\d)","0$1"));
        }
    }
}



发表于 2020-02-27 21:38:00 回复(0)
whileTrue:
    try:
        N =eval(input())
        whileN>0:
            time =input()
            H =time[0:2]
            M =time[3:5]
            S =time[6:8]
            ifint(H)>23:
                #H = H%10
                H ='0'+str(int(H)%10)
            ifint(M)>59:
                #M = M%10
                M ='0'+str(int(M)%10)
            ifint(S)>59:
                S ='0'+str(int(S)%10)
            print(H+':'+M+':'+S)
            N-=1
    except:
        break
就是超过23、59、59就%10,并且补零
发表于 2018-12-04 09:28:26 回复(0)
WAK头像 WAK
将数据读入后,按位进行转换,第1位0~2,第2位0~9(第1位0或1)或0~3(第1位2),第3位0~5,第4位0~9,第5位0~5,第6位0~9;
但有一种情况要注意,当第1位=2且第2位>3时,可以第1位不变,第2位置0;也可以第1位置0,第2位不变,显然第2种方法字典序更小,除了这种情况,其他按位的范围取就可以。
#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    while(cin>>t){
        for(int T = 0;T<t;T++){
            int a,b,c,d,e,f;
            string s;
            cin>>s;
            a = s[0]-'0';
            b = s[1]-'0';
            c = s[3]-'0';
            d = s[4]-'0';
            e = s[6]-'0';
            f = s[7]-'0';
            int tou[10]={0,1,2,0,0,0,0,0,0,0};    //第1位的取值
            int tou2[10] = {0,1,2,3,0,0,0,0,0,0}; //当第1位=2时,第2位的取值
            int ji[10]={0,1,2,3,4,5,0,0,0,0};     //剩下奇数位的取值
            int aa,bb,cc,dd,ee,ff;
            if(a==2&&b>3)     //当第1位=2且第2位>3时,将第1位置0
                aa = 0;
            else
                aa = tou[a];
            if(aa==0||aa==1)   //当第1位=0或1时
                bb = b;
            else               //当第1位=2时
                bb = tou2[b];
            cc = ji[c];        //0~5
            dd = d;
            ee = ji[e];        //0~5
            ff = f;
            printf("%d%d:%d%d:%d%d\n",aa,bb,cc,dd,ee,ff);
        }
    }
    system("pause");
    return 0;
}

发表于 2018-07-31 10:44:31 回复(4)
//注意 s[0]=2,s1[1]<=3这种情况


#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool is_time(const string& s)
{
    //flag = true;
    if (s[0] < '2'&&s[0] >= '0');
    else return false;

    if (s[0] == '2'&&s[1]<= '3');
    else return false;


    if (s[3] >= '0'&&s[3] <= '5');
    else return false;

    if (s[4] <= '9'&&s[4] >= '0');
    else return false;

    if (s[6] <= '5'&&s[6] >= '0');
    else return false;

    if (s[7] <= '9'&&s[7] >= '0');
    else return false;

    return true;
}


void func(string& str)
{
    if (str[0]>'2')
        str[0] = '0';
    if (str[0] == '2'&&str[1]>'3')
        str[0] = '0';
    if (str[3]>'5')
        str[3] = '0';
    if (str[6]>'5')
        str[6] = '0';
}



int main()
{
    //int n1;
    int n;
    // cin>>n1;
    cin >> n;
    while (n--)
    {
        string s;
        cin >> s;
        if (is_time(s))
            cout << s << endl;
        else {
            func(s);
            cout << s << endl;
        }
        
    }
    system("pause");
    return 0;
}
 
发表于 2018-08-01 23:28:59 回复(1)
分别检查时分秒是否合法(小时满足24进制,分钟和秒满足60进制),如果超出对应的范围,要想字典序小,直接把高位改成0就可以了
def isValid(h, m, s):
    if 0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60:
        return True
    else:
        return False

if __name__ == "__main__":
    T = int(input())
    while T:
        raw_time = input()
        hh, mm, ss = map(int, raw_time.split(":"))
        if isValid(hh, mm, ss):
            print(raw_time)
        else:
            new_time = ""
            if hh > 23:
                new_time += f"0{hh % 10}:"
            else:
                new_time += f"0{str(hh)}:" if hh < 10 else f"{str(hh)}:"
            if mm > 59:
                new_time += f"0{mm % 10}:"
            else:
                new_time += f"0{str(mm)}:" if mm < 10 else f"{str(mm)}:"
            if ss > 59:
                new_time += f"0{ss % 10}"
            else:
                new_time += f"0{str(ss)}" if ss < 10 else f"{str(ss)}"
            print(new_time)
        T -= 1

发表于 2022-01-08 10:44:05 回复(0)
JavaScript(Node) 😎题目:网易游戏🎮-时钟(padStart自动补全)
const readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    ouput: process.stdout
})
let inArr = []
let n
rl.on('line',line=>{
    if(!line) return
    inArr.push(line.trim())
    n = +inArr[0]
    if(inArr.length === n+1){
        let arr = []
        let res = []
        let i = 0
        while (i<n) {
            arr[i] = inArr[i+1].split(':').map(e => +e)
            arr[i][0] = arr[i][0] > 23 ? '0'+ arr[i][0]%10 :arr[i][0]
            arr[i][1] = arr[i][1] > 59 ? '0'+ arr[i][1]%10 :arr[i][1]
            arr[i][2] = arr[i][2] > 59 ? '0'+ arr[i][2]%10 :arr[i][2]
            res = arr[i][0].toString().padStart(2,'0')+':'+arr[i][1].toString().padStart(2,'0')+':'+arr[i][2].toString().padStart(2,'0')
            console.log(res)
            i++
        }
    }
})


发表于 2020-03-01 14:50:39 回复(0)
思路其实很直观,首先想到对于时H,H1(这里用1,2代指位置,后面不在赘述)只要大于2肯定是
无效时间,H2如果在H1==2的情况下大于3也是无效的,同样的考虑M1大于5是无效的,M2无论怎
么取都可以(0-9),S1也是大于5是无效的,S2无论怎么取都可以(0-9)。至于无效之后当然
是调整为0,这样字典序肯定最小。
那么很自然的我们对于这些无效的情况都做检查,假如发生通通纠正就可以。
但是这里有一个藏起来的“陷阱”,一开始可能没考虑到,就是对于H1,H2,假如H1大于2无效,
要调整,那么当H1==2,H2大于3的情况,我们调整H2吗?并不是,我们此时还是调整H1,把H1调
为0,则H2自然是有效的,再考虑完这个情况就可以了。

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<string> input;
    string tmp;
    for(int i=0;i<n;i++)
    {
        cin>>tmp;
        input.push_back(tmp);
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<8;j++)
        {
            if(j==0&&input[i][j]>'2')
                input[i][j]='0';
            if(j==1&&input[i][j]>'3'&&input[i][j-1]=='2')
                input[i][j-1]='0';
            if(j==3&&input[i][j]>'5')
                input[i][j]='0';
            if(j==6&&input[i][j]>'5')
                input[i][j]='0';
        }
    }
    for(int i=0;i<n;i++)
    {
        cout<<input[i]<<endl;
    }
}

发表于 2019-10-16 20:26:12 回复(0)
CJ-头像 CJ-
因为是按照字典序排,所以HH:MM:SS按照从左到右的顺序,依次比大小即可。
所以规则就是,先检查小时,大于等于24的一律把2变成0。然后分钟大于等于60的,把6变成0。最后检查秒,大于等于60的,把6变成0。
n = int(input())
for i in range(n):
    time = list(input())
    if int(time[0]) > 2:
        time[0] = "0"
    if int(time[0]) == 2:
        if int(time[1]) >= 4:
            time[0] = "0"
    if int(time[3]) >= 6:
        time[3] = "0"
    if int(time[6]) >= 6:
        time[6] = "0"
    print("".join(time))


编辑于 2019-09-14 10:02:42 回复(0)
题目简单 字符串第0、3 、6 非法置0 ,额外一种情况就是 时大于23 违法 代码简单易懂
#include <iostream>
using namespace std;
int main()
{
    int T;
    cin>>T;
    while (T--)
    {
        string time;
        cin>>time;
        if(time[0]>'2'||time[0]=='2'&&time[1]>'3')
            time[0]='0';

        if(time[3]>'5')
            time[3]='0';
        if(time[6]>'5')
            time[6]='0';
        cout<<time<<endl;
    }
    return 0;
}

发表于 2019-09-03 15:24:43 回复(0)

时钟 分 秒分开判断就好了,时钟超过:1、最高位超过30或者最高位为2时最低位超过4,直接修改最高位为0即是最低时间;   分和秒超的话直接判别高位位0就行了。

#include <iostream>

using namespace std;

void change(string s)
{
    if(s[0] > '2' || (s[0] > '1' && s[1] > '3')) s[0] = '0';
    s[3] = s[3]<'6'?s[3]:'0';
    s[6] = s[6]<'6'?s[6]:'0';
    cout << s << endl;
}

int main()
{
    int n ; cin>>n;
    string s;
    while(cin >>s) change(s);
}


编辑于 2019-08-08 22:07:29 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {


    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(bf.readLine());
        for (int i = 0; i < n; i++) {
            String s = bf.readLine();
            System.out.println(correcTime(s));
        }
    }

    //只要时钟大于23或者分钟秒钟大于59就把第一位置0
    private static String correcTime(String s) {
        StringBuilder sb = new StringBuilder();
        String[] times = s.split(":");
        sb.append(times[0].compareTo("23") > 0 ? "0" : times[0].charAt(0)).append(times[0].charAt(1)).append(":");
        sb.append(times[1].compareTo("59") > 0 ? "0" : times[1].charAt(0)).append(times[1].charAt(1)).append(":");
        sb.append(times[2].compareTo("59") > 0 ? "0" : times[2].charAt(0)).append(times[2].charAt(1));
        return sb.toString();
    }
}
编辑于 2019-08-06 14:44:28 回复(0)
#include<iostream>
using namespace std;
int main(){
    int n,h,m,s;//h为小时,m为分,s为秒
            cin>>n;
        char **str = new char*[n];//定义一个2维数组str[]用于储存n个时间
        for(int i=0;i<n;i++)
        {
            str[i] = new char[8];
        }
    for(int i=0;i<n;i++){
        for(int x=0;x<=7;x++){
        cin>>str[i][x];}//依次输入每个时间
        h=(str[i][0]-'0')*10+(str[i][1]-'0');//将输入的char类型的时间的小时转换成整数储存赋值给h
        m=(str[i][3]-'0')*10+(str[i][4]-'0');
        s=(str[i][6]-'0')*10+(str[i][7]-'0');
        if(h>23){str[i][0]=0+'0';}
        if(m>59){str[i][3]=0+'0';}
        if(s>59){str[i][6]=0+'0';}
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<=7;j++){
            cout<<str[i][j];//输出n个时间字符串
        }
        cout<<endl;//为了和答案一样的输入和输出,必须要换行(就差这一步,牛客网也不给通过多的)
}
    delete []str;
}
发表于 2019-07-29 16:28:52 回复(2)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            char[] time = scanner.next().toCharArray();
            time[0] = (time[0] > '2' || (time[0] == '2' && time[1] > '3')) ? '0' : time[0];
            time[3] = (time[3] > '5') ? '0' : time[3];
            time[6] = (time[6] > '5') ? '0' : time[6];
            System.out.println(String.valueOf(time));
        }
    }
}
发表于 2019-07-12 10:12:43 回复(0)
import java.util.Scanner;

public class Main {

    public static String process(String str) {
        int hour = Integer.valueOf(str.substring(0, 2));
        int min = Integer.valueOf(str.substring(3, 5));
        int second = Integer.valueOf(str.substring(6, 8));
        char[] ch = str.toCharArray();
        if (hour > 23) {
            ch[0] = '0';
        }
        if (min > 59) {
            ch[3] = '0';
        }
        if (second > 59) {
            ch[6] = '0';
        }
        return String.valueOf(ch);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n-- > 0) {
            String str = sc.next();
            System.out.println(process(str));
        }
    }
}
发表于 2019-07-06 19:56:58 回复(0)
//特别简单啦,题目上都说了
    //"其中时的范围为[‘00’,‘01’…‘23’],分的范围为[‘00’,‘01’…‘59’],秒的范围为[‘00’,‘01’…‘59’]。"
所以取个余数就好啦。
#include <stdio.h> using namespace std; int main() {     int n,h,m,t;     scanf("%d",&n);     while (n--)     {         scanf("%d:%d:%d",&h,&m,&t);         if (h > 23) h %= 10;         if (m > 59) m %= 10;         if (t > 59) t %= 10;         printf("%02d:%02d:%02d\n",h,m,t);     }     return 0; } 

发表于 2018-08-13 21:16:14 回复(0)