ASCII String to Integer Conversion Algorithm


You are given a string s containing digits from “0” to “9” and lowercase alphabet characters. Return the sum of the numbers found in s.

Constraints
1 ≤ n ≤ 100,000 where n is the length of s
Example 1
Input
s = “11aa32bbb5”
Output
48
Explanation
Since 11 + 32 + 5 = 48.

Example 2
Input
s = “abc”
Output
0
Explanation
There’s no digits so it defaults to 0.

Example 3
Input
s = “1a2b30”
Output
33
Explanation
Since 1 + 2 + 30 = 33.

Sum of Integer in ASCII String

Let’s iterate the string character by character – and if it is a digit type, we adjust the current integer (ASCII code minus ‘0’) otherwise we add it to the sum. The following C++ takes O(N) time and O(1) space. The isdigit function is same as checking if a character is between ‘0’ and ‘9’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int asciiStringToInteger(string s) {
    int ans = 0;
    int n = static_cast<int>(s.size());
    int cur = 0;
    for (int i = 0; i < n; ++ i) {
        if (isdigit(s[i])) {
            cur = cur * 10 + s[i] - '0';
        } else {
            ans += cur;
            cur = 0;
        }
    }
    ans += cur;
    return ans;
}
int asciiStringToInteger(string s) {
    int ans = 0;
    int n = static_cast<int>(s.size());
    int cur = 0;
    for (int i = 0; i < n; ++ i) {
        if (isdigit(s[i])) {
            cur = cur * 10 + s[i] - '0';
        } else {
            ans += cur;
            cur = 0;
        }
    }
    ans += cur;
    return ans;
}

Python implementation of the same idea. Remember that the string has isdigit() method.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def asciiStringToInteger(self, s):
        ans = 0
        cur = 0
        for i in s:
            if i.isdigit():
                cur = cur * 10 + int(i)
            else:
                ans += cur
                cur = 0
        ans += cur
        return ans
class Solution:
    def asciiStringToInteger(self, s):
        ans = 0
        cur = 0
        for i in s:
            if i.isdigit():
                cur = cur * 10 + int(i)
            else:
                ans += cur
                cur = 0
        ans += cur
        return ans

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
299 words
Last Post: Teaching Kids Programming - Construct Binary Tree From Pre/Inorder Traversals
Next Post: Minimum Letters to Delete to Get A's before B's with Dynamic Programming Algorithm

The Permanent URL is: ASCII String to Integer Conversion Algorithm

Leave a Reply