{ }codelper
判断函数参数返回值P0149

会议室预约时间检查器

会议室预约请求以 "HH:MM-HH:MM" 形式(开始时刻-结束时刻)的字符串送来。
第一行给出请求数 n,接下来 n 行每行给出一个请求。
对每个请求,从第 1 条开始依次检查下面六条规则。
1.
格式:恰好 11 个字符,第 3 个和第 9 个字符是 ':',第 6 个字符是 '-',其余 8 个字符都是数字(0~9)。
2.
时刻:两个时刻的小时(HH)都在 00 ~ 23,分钟(MM)都在 00 ~ 59。
3.
15 分钟为单位:两个时刻的分钟都是 00、15、30、45 之一。
4.
顺序:开始时刻早于结束时刻。
5.
营业时间:开始时刻在 09:00 或之后,结束时刻在 18:00 或之前。
6.
时长:预约时长不超过 3 小时(180 分钟)。
对每个请求,在一行中输出它第一个违反的规则编号;全部遵守则输出 0。
最后一行输出全部遵守的请求数。
程序要拆成返回真假的小函数(如“是不是数字”“格式对不对”“是不是合法时刻”)和一个返回第一个违反的规则编号的函数。

输入
1 ≤ n ≤ 100。
每个请求是由 1 ~ 20 个非空白字符(ASCII 码 33 ~ 126)组成的字符串
输出
n + 1 行:每个请求输出 0 ~ 6 之一,最后一行是全部遵守的请求数
样例 1 · stdin
8
10:00-11:30
9:00-10:00
09:00-10:60
13:10-14:00
15:00-15:00
08:45-10:00
12:00-15:15
15:00-18:00
stdout
0
1
2
3
4
5
6
0
2
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

这道题把返回真假的小函数组合成一个大检查。
布尔类型:Python bool(True/False),JS/TS boolean,Java boolean,C# bool,C++ bool,C 用 stdbool.h 的 bool(以前用 int 的 0/1),Craykon 真/假(韩语 참/거짓)。
要先问长度,s[2] 才安全。
&&、and、|| 一旦前面能确定结果就不看后面,所以长度不对时不会去读字符。
陷阱一:如果顺序反过来先看 s[2],遇到短字符串时 Python 抛 IndexError,Java 抛 StringIndexOutOfBoundsException,C# 抛 IndexOutOfRangeException,JS 得到 undefined,C 会读到字符串末尾之外。
陷阱二:不要把“是不是数字”交给转换函数。
Python 的 int("+9")、int("-1") 会返回 9 和 -1,JS 的 parseInt("1a") 只读开头的 1,C 的 sscanf("%d:%d-%d:%d") 也接受 +9。
要另写一个函数,对每个字符判断 '0' <= ch <= '9'。
Craykon 也用字符串大小比较写成 ch >= "0" && ch <= "9"。
陷阱三:18:00 结束的预约和恰好 180 分钟的预约都是允许的,所以用 <=。

Pythonmain.py · 46 行
def is_digit(ch):    return "0" <= ch <= "9"   # 아스키 숫자만(str.isdigit은 다른 숫자 글자도 참)  def well_formed(s):    """규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 s[2]가 안전하다."""    if len(s) != 11 or s[2] != ":" or s[5] != "-" or s[8] != ":":        return False    return all(is_digit(s[i]) for i in (0, 1, 3, 4, 6, 7, 9, 10))  def valid_clock(h, m):    return 0 <= h <= 23 and 0 <= m <= 59  def on_grid(m):    return m % 15 == 0  def first_broken(s):    """처음 어긴 규칙 번호, 모두 지키면 0."""    if not well_formed(s):        return 1    h1, m1, h2, m2 = int(s[0:2]), int(s[3:5]), int(s[6:8]), int(s[9:11])    if not (valid_clock(h1, m1) and valid_clock(h2, m2)):        return 2    if not (on_grid(m1) and on_grid(m2)):        return 3    start, end = h1 * 60 + m1, h2 * 60 + m2    if not start < end:        return 4    if not (start >= 9 * 60 and end <= 18 * 60):        return 5    if end - start > 180:        return 6    return 0  n = int(input())passed = 0for _ in range(n):    r = first_broken(input().strip())    print(r)    if r == 0:        passed += 1print(passed)
JavaScriptmain.js · 31 行
const lines = require("fs").readFileSync(0, "utf8").split("\n"); const isDigit = (ch) => ch >= "0" && ch <= "9"; // 규칙 1: HH:MM-HH:MM 꼴인가function wellFormed(s) {  if (s.length !== 11 || s[2] !== ":" || s[5] !== "-" || s[8] !== ":") return false;  return [0, 1, 3, 4, 6, 7, 9, 10].every((i) => isDigit(s[i]));} const validClock = (h, m) => h >= 0 && h <= 23 && m >= 0 && m <= 59;const onGrid = (m) => m % 15 === 0; // 처음 어긴 규칙 번호, 모두 지키면 0function firstBroken(s) {  if (!wellFormed(s)) return 1;  const [h1, m1, h2, m2] = [0, 3, 6, 9].map((i) => Number(s.slice(i, i + 2)));  if (!(validClock(h1, m1) && validClock(h2, m2))) return 2;  if (!(onGrid(m1) && onGrid(m2))) return 3;  const start = h1 * 60 + m1;  const end = h2 * 60 + m2;  if (!(start < end)) return 4;  if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;  if (end - start > 180) return 6;  return 0;} const n = Number(lines[0]);const out = lines.slice(1, n + 1).map((line) => firstBroken(line.trim()));out.push(out.filter((r) => r === 0).length);console.log(out.join("\n"));
TypeScriptmain.ts · 32 行
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n"); const isDigit = (ch: string): boolean => ch >= "0" && ch <= "9"; // 규칙 1: HH:MM-HH:MM 꼴인가function wellFormed(s: string): boolean {  if (s.length !== 11 || s[2] !== ":" || s[5] !== "-" || s[8] !== ":") return false;  return [0, 1, 3, 4, 6, 7, 9, 10].every((i) => isDigit(s[i]));} const validClock = (h: number, m: number): boolean => h >= 0 && h <= 23 && m >= 0 && m <= 59;const onGrid = (m: number): boolean => m % 15 === 0; // 처음 어긴 규칙 번호, 모두 지키면 0function firstBroken(s: string): number {  if (!wellFormed(s)) return 1;  const [h1, m1, h2, m2] = [0, 3, 6, 9].map((i) => Number(s.slice(i, i + 2)));  if (!(validClock(h1, m1) && validClock(h2, m2))) return 2;  if (!(onGrid(m1) && onGrid(m2))) return 3;  const start = h1 * 60 + m1;  const end = h2 * 60 + m2;  if (!(start < end)) return 4;  if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;  if (end - start > 180) return 6;  return 0;} const n = Number(lines[0]);const out: number[] = lines.slice(1, n + 1).map((line) => firstBroken(line.trim()));out.push(out.filter((r) => r === 0).length);console.log(out.join("\n"));
JavaMain.java · 55 行
import java.io.*; public class Main {    static boolean isDigit(char ch) {        return ch >= '0' && ch <= '9'; // Character.isDigit은 다른 나라 숫자도 참    }     // 규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 charAt(2)가 안전하다    static boolean wellFormed(String s) {        if (s.length() != 11 || s.charAt(2) != ':' || s.charAt(5) != '-' || s.charAt(8) != ':') return false;        for (int i : new int[] {0, 1, 3, 4, 6, 7, 9, 10}) {            if (!isDigit(s.charAt(i))) return false;        }        return true;    }     static boolean validClock(int h, int m) {        return h >= 0 && h <= 23 && m >= 0 && m <= 59;    }     static boolean onGrid(int m) {        return m % 15 == 0;    }     static int two(String s, int i) {        return (s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0');    }     // 처음 어긴 규칙 번호, 모두 지키면 0    static int firstBroken(String s) {        if (!wellFormed(s)) return 1;        int h1 = two(s, 0), m1 = two(s, 3), h2 = two(s, 6), m2 = two(s, 9);        if (!(validClock(h1, m1) && validClock(h2, m2))) return 2;        if (!(onGrid(m1) && onGrid(m2))) return 3;        int start = h1 * 60 + m1, end = h2 * 60 + m2;        if (!(start < end)) return 4;        if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;        if (end - start > 180) return 6;        return 0;    }     public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        int passed = 0;        for (int i = 0; i < n; i++) {            int r = firstBroken(br.readLine().trim());            out.append(r).append('\n');            if (r == 0) passed++;        }        out.append(passed).append('\n');        System.out.print(out);    }}
C#Main.cs · 49 行
using System;using System.Linq;using System.Text; class Program{    static bool IsDigit(char ch) => ch >= '0' && ch <= '9'; // char.IsDigit은 다른 나라 숫자도 참     // 규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 s[2]가 안전하다    static bool WellFormed(string s)    {        if (s.Length != 11 || s[2] != ':' || s[5] != '-' || s[8] != ':') return false;        return new[] { 0, 1, 3, 4, 6, 7, 9, 10 }.All(i => IsDigit(s[i]));    }     static bool ValidClock(int h, int m) => h >= 0 && h <= 23 && m >= 0 && m <= 59;     static bool OnGrid(int m) => m % 15 == 0;     // 처음 어긴 규칙 번호, 모두 지키면 0    static int FirstBroken(string s)    {        if (!WellFormed(s)) return 1;        int h1 = int.Parse(s.Substring(0, 2)), m1 = int.Parse(s.Substring(3, 2));        int h2 = int.Parse(s.Substring(6, 2)), m2 = int.Parse(s.Substring(9, 2));        if (!(ValidClock(h1, m1) && ValidClock(h2, m2))) return 2;        if (!(OnGrid(m1) && OnGrid(m2))) return 3;        int start = h1 * 60 + m1, end = h2 * 60 + m2;        if (!(start < end)) return 4;        if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;        if (end - start > 180) return 6;        return 0;    }     static void Main()    {        int n = int.Parse(Console.ReadLine().Trim());        var sb = new StringBuilder();        int passed = 0;        for (int i = 0; i < n; i++)        {            int r = FirstBroken(Console.ReadLine().Trim());            sb.Append(r).Append('\n');            if (r == 0) passed++;        }        sb.Append(passed).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 44 行
#include <iostream>#include <string> bool is_digit(char ch) { return ch >= '0' && ch <= '9'; } // 규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 s[2]가 안전하다bool well_formed(const std::string& s) {    if (s.size() != 11 || s[2] != ':' || s[5] != '-' || s[8] != ':') return false;    for (int i : {0, 1, 3, 4, 6, 7, 9, 10})        if (!is_digit(s[i])) return false;    return true;} bool valid_clock(int h, int m) { return h >= 0 && h <= 23 && m >= 0 && m <= 59; } bool on_grid(int m) { return m % 15 == 0; } int two(const std::string& s, int i) { return (s[i] - '0') * 10 + (s[i + 1] - '0'); } // 처음 어긴 규칙 번호, 모두 지키면 0int first_broken(const std::string& s) {    if (!well_formed(s)) return 1;    int h1 = two(s, 0), m1 = two(s, 3), h2 = two(s, 6), m2 = two(s, 9);    if (!(valid_clock(h1, m1) && valid_clock(h2, m2))) return 2;    if (!(on_grid(m1) && on_grid(m2))) return 3;    int start = h1 * 60 + m1, end = h2 * 60 + m2;    if (!(start < end)) return 4;    if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;    if (end - start > 180) return 6;    return 0;} int main() {    int n, passed = 0;    std::cin >> n;    for (int i = 0; i < n; i++) {        std::string s;        std::cin >> s; // 빈칸 없는 문자열        int r = first_broken(s);        std::cout << r << "\n";        if (r == 0) passed++;    }    std::cout << passed << "\n";}
Cmain.c · 47 行
#include <stdbool.h>#include <stdio.h>#include <string.h> static bool is_digit(char ch) { return ch >= '0' && ch <= '9'; } /* 규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 s[2]가 안전하다 */static bool well_formed(const char *s) {    if (strlen(s) != 11 || s[2] != ':' || s[5] != '-' || s[8] != ':') return false;    const int at[] = {0, 1, 3, 4, 6, 7, 9, 10};    for (int i = 0; i < 8; i++)        if (!is_digit(s[at[i]])) return false;    return true;} static bool valid_clock(int h, int m) { return h >= 0 && h <= 23 && m >= 0 && m <= 59; } static bool on_grid(int m) { return m % 15 == 0; } static int two(const char *s, int i) { return (s[i] - '0') * 10 + (s[i + 1] - '0'); } /* 처음 어긴 규칙 번호, 모두 지키면 0 */static int first_broken(const char *s) {    if (!well_formed(s)) return 1;    int h1 = two(s, 0), m1 = two(s, 3), h2 = two(s, 6), m2 = two(s, 9);    if (!(valid_clock(h1, m1) && valid_clock(h2, m2))) return 2;    if (!(on_grid(m1) && on_grid(m2))) return 3;    int start = h1 * 60 + m1, end = h2 * 60 + m2;    if (!(start < end)) return 4;    if (!(start >= 9 * 60 && end <= 18 * 60)) return 5;    if (end - start > 180) return 6;    return 0;} int main(void) {    int n, passed = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        char s[32];        scanf("%31s", s); /* 빈칸 없는 문자열, 많아야 20글자 */        int r = first_broken(s);        printf("%d\n", r);        if (r == 0) passed++;    }    printf("%d\n", passed);    return 0;}
Craykonmain.cray · 80 行
숫자인가(ch){    返回 ch >= "0" && ch <= "9";} // 규칙 1: HH:MM-HH:MM 꼴인가. 길이부터 물어야 s[2]가 안전하다꼴이맞나(s){    如果 (s.长度 != 11 || s[2] != ":" || s[5] != "-" || s[8] != ":")    {        返回 假;    }    遍历 (i 在 [0, 1, 3, 4, 6, 7, 9, 10])    {        如果 (!숫자인가(s[i]))        {            返回 假;        }    }    返回 真;} 시각인가(h, m){    返回 h >= 0 && h <= 23 && m >= 0 && m <= 59;} 십오분단위인가(m){    返回 m % 15 == 0;} // 처음 어긴 규칙 번호, 모두 지키면 0처음어긴규칙(s){    如果 (!꼴이맞나(s))    {        返回 1;    }    h1 = s.截取(0, 2).转数字();    m1 = s.截取(3, 2).转数字();    h2 = s.截取(6, 2).转数字();    m2 = s.截取(9, 2).转数字();    如果 (!(시각인가(h1, m1) && 시각인가(h2, m2)))    {        返回 2;    }    如果 (!(십오분단위인가(m1) && 십오분단위인가(m2)))    {        返回 3;    }    start = h1 * 60 + m1;    end = h2 * 60 + m2;    如果 (!(start < end))    {        返回 4;    }    如果 (!(start >= 9 * 60 && end <= 18 * 60))    {        返回 5;    }    如果 (end - start > 180)    {        返回 6;    }    返回 0;} n = 控制台.读行().转数字();passed = 0;循环 (i = 0; i < n; i++){    r = 처음어긴규칙(控制台.读行().去空白());    控制台.输出(r);    如果 (r == 0)    {        passed++;    }}控制台.输出(passed);