Retour aux défis
Facile 0 résolus 0 % de réussite

Sum the Valid Numbers

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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).

Contraintes

0 ≤ number of entries ≤ 1,000

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

Exemples

Exemple 1
Entrée :
values = ["10", " 5 ", "abc", "-3"]

Sortie attendue :
expected = 12
Entrée :
std::vector<std::string> values = {"10", " 5 ", "abc", "-3"};

Sortie attendue :
long long expected = 12;
Entrée :
string[] values = new string[] {"10", " 5 ", "abc", "-3"};

Sortie attendue :
long expected = 12;

Explication

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

Exemple 2
Entrée :
values = ["2.5", "", "seven"]

Sortie attendue :
expected = 0
Entrée :
std::vector<std::string> values = {"2.5", "", "seven"};

Sortie attendue :
long long expected = 0;
Entrée :
string[] values = new string[] {"2.5", "", "seven"};

Sortie attendue :
long expected = 0;

Explication

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

Comment l'aborder

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

Indice 1

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

Indice 2

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

Indice 3

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

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.