解题思路

  1. 这是一个时钟显示修复问题,需要将不合法的时间修改为合法时间
  2. 对于每个时间:
    • 如果小时超过23,取个位数
    • 如果分钟超过59,取个位数
    • 如果秒数超过59,取个位数
  3. 修改后的时间需要保持格式:HH:MM:SS,不足两位需要补0

代码

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int n, h, m, s;
    cin >> n;
    while(n--) {
        scanf("%d:%d:%d", &h, &m, &s);
        
        // 修复不合法的时间
        if(h > 23) h %= 10;
        if(m > 59) m %= 10;
        if(s > 59) s %= 10;
        
        // 输出修复后的时间,保持两位数格式
        printf("%02d:%02d:%02d\n", h, m, s);
    }
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        
        while(n-- > 0) {
            String[] time = sc.nextLine().split(":");
            int h = Integer.parseInt(time[0]);
            int m = Integer.parseInt(time[1]);
            int s = Integer.parseInt(time[2]);
            
            // 修复不合法的时间
            if(h > 23) h %= 10;
            if(m > 59) m %= 10;
            if(s > 59) s %= 10;
            
            // 输出修复后的时间
            System.out.printf("%02d:%02d:%02d\n", h, m, s);
        }
    }
}
n = int(input())
for _ in range(n):
    h, m, s = map(int, input().split(':'))
    
    # 修复不合法的时间
    if h > 23: h %= 10
    if m > 59: m %= 10
    if s > 59: s %= 10
    
    # 输出修复后的时间
    print(f"{h:02d}:{m:02d}:{s:02d}")

算法及复杂度

  • 算法:简单的数值处理
  • 时间复杂度: - 为测试用例数量
  • 空间复杂度: - 只需要常数额外空间