1181. Numbers in the Noise

Easy1.5 points estimatedStringMaths

A scanner has read a noisy receipt and produced the string s, which mixes letters, punctuation, spaces and digits. Treat every maximal run of consecutive digits as one non-negative decimal number. Signs and decimal points are not part of a number, so "-5" contributes 5 and "3.25" contributes the two numbers 3 and 25.

Leading zeros are allowed and do not change the value: in "a12b003" the numbers are 12 and 3, so the sum is 15. Return the sum of all such numbers as a long, or 0 when the string has no digits.

Each digit run has at most 12 digits and the total stays below 2^53. One left-to-right pass accumulates the current number and adds it when the run ends, in linear time and constant space.

Example 1

Input:
s = "a12b003"
Output:
15
Explanation:

The digit runs are 12 and 003, which are the numbers 12 and 3, so the sum is 15.

Example 2

Input:
s = "-5 and +7 make 2"
Output:
14
Explanation:

Signs are ignored: the numbers are 5, 7 and 2, giving 14.

Example 3

Input:
s = "no digits"
Output:
0
Explanation:

There are no digits, so the sum is 0.

Constraints

1 ≤ s.length ≤ 104

Every digit run has at most 12 digits

The total sum is below 253

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…