모든 챌린지
쉬움 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

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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.