Tous les défis
Facile 0 résolus 0 % de réussite

First Invalid Age

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

0 ≤ number of entries ≤ 10,000

Each entry has at most 20 characters

Exemples

Exemple 1
Entrée :
values = ["25", " 40 ", "abc", "200"]

Sortie attendue :
expected = 2
Entrée :
std::vector<std::string> values = {"25", " 40 ", "abc", "200"};

Sortie attendue :
long long expected = 2;
Entrée :
string[] values = new string[] {"25", " 40 ", "abc", "200"};

Sortie attendue :
long expected = 2;

Explication

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

Exemple 2
Entrée :
values = ["0", "150", "007"]

Sortie attendue :
expected = -1
Entrée :
std::vector<std::string> values = {"0", "150", "007"};

Sortie attendue :
long long expected = -1;
Entrée :
string[] values = new string[] {"0", "150", "007"};

Sortie attendue :
long expected = -1;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

Only after that, compare its value with 150.

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.