You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决24小时制时钟加分钟边缘用例问题:部分用例失败

编程挑战问题排查

我正在解决一个Python入门编程挑战,所有公开输入用例(小时、分钟、添加分钟)均已通过:

  • 14, 28, 75 = 15:43
  • 14, 28, 1440 = 14:28
  • 7, 50, 5320 = 0:30
  • 23, 58, 2 = 0:0
  • (评论区示例)18, 12, 1139 = 13:11

但仍有未公开的边缘用例未通过,我的Python代码如下:

# 处理输入,按单位取模
hours = int(input()) % 24
mins = int(input()) % 60 
addMins = int(input()) % 1440 

# 计算添加分钟后的时间
newMins = (mins + addMins) % 60
newHours =  hours + (addMins // 60)
newHours = newHours % 23

print(newHours, ':', newMins, sep='')

问题分析

代码核心错误是newHours = newHours % 23——一天有24小时,取模应使用24而非23。比如当计算后小时数为24时,24 % 23会得到1,但正确结果应为0(对应午夜),这类场景就是导致私有边缘用例失败的原因。

修正方案

直接将取模的23改为24即可:

# 处理输入,按单位取模
hours = int(input()) % 24
mins = int(input()) % 60 
addMins = int(input()) % 1440 

# 计算添加分钟后的时间
newMins = (mins + addMins) % 60
newHours =  hours + (addMins // 60)
newHours = newHours % 24  # 此处改为24

print(newHours, ':', newMins, sep='')

或者采用更严谨的总分钟数计算方式:

# 处理输入,按单位取模
hours = int(input()) % 24
mins = int(input()) % 60 
addMins = int(input()) % 1440 

# 转为总分钟数统一计算
total_minutes = hours * 60 + mins + addMins
total_minutes %= 1440  # 限制在一天的分钟数范围内
newHours = total_minutes // 60
newMins = total_minutes % 60

print(f"{newHours}:{newMins}")

内容的提问来源于stack exchange,提问作者SamAndrew81

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:15:46