ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก