Given an alphanumeric string made up of digits and lower case ASCII characters only, find the sum of all the digit characters in the string. The function signature for 'sum Digits' is -

(define sumDigits ...)

1. Constraints -
- Not allowed to use library functions. This means no import statement.
- No loops or list comprehension. The solution must be recursive.
- Do not use length of string in any function.


2. Input to function 'sumDigits -
- An alphanumeric string.


3. Output of function -
-Sum of all the digits in the string.


4. Sample test case
Test case 1
calling sumDigits ab1c2d3e54 outputs 15 = 1 + 2 + 3 + 5 + 4

Respuesta :

Answer:

C++.

Explanation:

#include <iostream>

#include <string>

using namespace std;

////////////////////////////////////////////////////////////////////////////

int sumDigits(string alphanumeric) {

   if (alphanumeric.length() == 1) {

       if ((int(alphanumeric[0]) >= 48) && (int(alphanumeric[0]) <= 57)) {

           cout<<int(alphanumeric[0]) - 48<<endl;

           return (int(alphanumeric[0]) - 48);

       }

       else

           return 0;

   }

   else {

       if ((int(alphanumeric[0]) >= 48) && (int(alphanumeric[0]) <= 57)) {

           cout<<int(alphanumeric[0]) - 48<<endl;

           return int(alphanumeric[0]) - 48 + sumDigits(alphanumeric.substr(1, alphanumeric.length()-1));

       }

       else

           return 0 + sumDigits(alphanumeric.substr(1, alphanumeric.length()-1));

   }

}

////////////////////////////////////////////////////////////////////////////

int main() {

   cout<<"Sum: "<<sumDigits("ab1c2d3e54");

   return 0;

}