1 条题解

  • 0
    @ 2025-9-16 0:59:43

    核心逻辑

    1. 将两个时刻(xx:yy:zz)分别转换为总秒数(小时×3600 + 分钟×60 + 秒);
    2. 用结束时刻的总秒数减去开始时刻的总秒数,得到时间差(秒)。

    代码实现

    C

    #include <stdio.h>
    
    // 将"xx:yy:zz"格式转换为总秒数
    int to_seconds(int h, int m, int s) {
        return h * 3600 + m * 60 + s;
    }
    
    int main() {
        int h1, m1, s1;  // 开始时间
        int h2, m2, s2;  // 结束时间
        
        // 读取时间格式(xx:yy:zz)
        scanf("%d:%d:%d", &h1, &m1, &s1);
        scanf("%d:%d:%d", &h2, &m2, &s2);
        
        // 计算总秒数并求差
        int start = to_seconds(h1, m1, s1);
        int end = to_seconds(h2, m2, s2);
        printf("%d\n", end - start);
        
        return 0;
    }
    

    C++

    #include <bits/stdc++.h>
    using namespace std;
    
    int to_seconds(int h, int m, int s) {
        return h * 3600 + m * 60 + s;
    }
    
    int main() {
        int h1, m1, s1, h2, m2, s2;
        char colon;  // 用于读取冒号
        
        // 读取格式:xx:yy:zz
        cin >> h1 >> colon >> m1 >> colon >> s1;
        cin >> h2 >> colon >> m2 >> colon >> s2;
        
        int start = to_seconds(h1, m1, s1);
        int end = to_seconds(h2, m2, s2);
        cout << end - start << endl;
        
        return 0;
    }
    

    Python

    def to_seconds(h, m, s):
        return h * 3600 + m * 60 + s
    
    # 读取两行时间
    time1 = input().strip()
    time2 = input().strip()
    
    # 分割为小时、分钟、秒
    h1, m1, s1 = map(int, time1.split(':'))
    h2, m2, s2 = map(int, time2.split(':'))
    
    # 计算差值
    start = to_seconds(h1, m1, s1)
    end = to_seconds(h2, m2, s2)
    print(end - start)
    

    验证(样例输入)

    • 开始时间12:34:56:12×3600 + 34×60 + 56 = 45296秒
    • 结束时间12:35:00:12×3600 + 35×60 + 0 = 45300秒
    • 差值:45300 - 45296 = 4,与样例输出一致。

    所有输入均按格式正确转换并计算差值,结果为两个时刻的秒数差。

    • 1

    信息

    ID
    447
    时间
    1000ms
    内存
    64MiB
    难度
    6
    标签
    递交数
    17
    已通过
    11
    上传者