쉬움 0명 해결 정답률 0%

First Invalid Age

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

배우게 될 내용

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

문제

번역본 보기

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.

제약 조건

0 ≤ number of entries ≤ 10,000

Each entry has at most 20 characters

예시

예시 1
입력:
values = ["25", " 40 ", "abc", "200"]

예상 출력:
expected = 2
입력:
std::vector<std::string> values = {"25", " 40 ", "abc", "200"};

예상 출력:
long long expected = 2;
입력:
string[] values = new string[] {"25", " 40 ", "abc", "200"};

예상 출력:
long expected = 2;

설명

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

예시 2
입력:
values = ["0", "150", "007"]

예상 출력:
expected = -1
입력:
std::vector<std::string> values = {"0", "150", "007"};

예상 출력:
long long expected = -1;
입력:
string[] values = new string[] {"0", "150", "007"};

예상 출력:
long expected = -1;

설명

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

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

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

힌트 2

Only after that, compare its value with 150.

힌트 3

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

예상 복잡도

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

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.