簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。