모든 챌린지
쉬움 1명 해결 정답률 14.3%

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에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 RCRiccardo Corti Python 838 ms - 4/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 1개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.