Dễ 1 người đã giải Tỷ lệ chấp nhận 14.3%

First Invalid Age

Validate typed ages and report where the first bad entry is instead of letting the program crash.

Bạn sẽ học được gì

  • Check that text contains only digits
  • Validate a number against a range
  • Report the position of the first bad entry

Đề bài

Xem bản dịch

A sign-up form receives ages as text. An entry is valid when, after trimming spaces at both ends, it consists only of digits (no sign) and its value is between 0 and 150 inclusive.

Find the first invalid entry so the form can point the user to it.

Implement first_invalid_age(values).

Input

values: The typed ages, in form order.

Output

Return the index of the first invalid entry, or -1 if all of them are valid.

Ràng buộc

0 ≤ number of entries ≤ 10,000

Each entry has at most 20 characters

Ví dụ

Ví dụ 1
Đầu vào:
values = ["25", " 40 ", "abc", "200"]

Kết quả mong đợi:
expected = 2
Đầu vào:
std::vector<std::string> values = {"25", " 40 ", "abc", "200"};

Kết quả mong đợi:
long long expected = 2;
Đầu vào:
string[] values = new string[] {"25", " 40 ", "abc", "200"};

Kết quả mong đợi:
long expected = 2;

Giải thích

"25" and " 40 " (spaces trimmed) are valid; "abc" at index 2 is the first invalid entry.

Ví dụ 2
Đầu vào:
values = ["0", "150", "007"]

Kết quả mong đợi:
expected = -1
Đầu vào:
std::vector<std::string> values = {"0", "150", "007"};

Kết quả mong đợi:
long long expected = -1;
Đầu vào:
string[] values = new string[] {"0", "150", "007"};

Kết quả mong đợi:
long expected = -1;

Giải thích

All three are digits between 0 and 150 (007 is 7), so the answer is -1.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Trim the entry, then check it is non-empty and made only of digits.

Gợi ý 2

Only after that, compare its value with 150.

Gợi ý 3

A minus sign makes the entry invalid, and 007 is a valid 7.

Độ phức tạp mong đợi

O(total length) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 RCRiccardo Corti Python 838 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.