簡単 0件解決済み 正答率0%

Sum the Valid Numbers

Add up the entries that are whole numbers and skip everything else, the way try/except handles bad input.

このチャレンジで学べること

  • Skip invalid input instead of crashing
  • Trim spaces before converting text to a number
  • Recognise an optional sign followed by digits

問題

翻訳を表示

Data typed by people is messy. You get a list of strings and must add up the ones that are whole numbers, ignoring the rest instead of crashing.

An entry counts if, after removing spaces at both ends, it is an optional + or - sign followed by one or more digits. Anything else (empty text, decimals such as "2.5", words) is skipped.

Implement sum_valid_numbers(values).

Input

values: The entries to read.

Output

Return the sum of the valid whole numbers (0 if there are none).

制約

0 ≤ number of entries ≤ 1,000

Each entry has at most 20 characters; valid numbers fit in a 64-bit integer

例

例 1
入力:
values = ["10", " 5 ", "abc", "-3"]

期待される出力:
expected = 12
入力:
std::vector<std::string> values = {"10", " 5 ", "abc", "-3"};

期待される出力:
long long expected = 12;
入力:
string[] values = new string[] {"10", " 5 ", "abc", "-3"};

期待される出力:
long expected = 12;

解説

"10", " 5 " (spaces are trimmed) and "-3" are whole numbers; "abc" is skipped. 10 + 5 - 3 = 12.

例 2
入力:
values = ["2.5", "", "seven"]

期待される出力:
expected = 0
入力:
std::vector<std::string> values = {"2.5", "", "seven"};

期待される出力:
long long expected = 0;
入力:
string[] values = new string[] {"2.5", "", "seven"};

期待される出力:
long expected = 0;

解説

None of the entries is a whole number, so the sum is 0.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Strip the spaces first, then decide whether what is left is a valid whole number.

ヒント 2

Converting inside try/except (or checking the characters) lets you skip bad entries without stopping.

ヒント 3

Remember that a lone sign such as "+" is not a number.

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

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