Question

**C++ only and no vectors or global variables. Thank you, Write a recursive function to convert...

**C++ only and no vectors or global variables. Thank you,

Write a recursive function to convert a character string of digits to an integer. Example: convert("1234) returns 1234. Hint: To convert a character to a number, subtract the ASCII value '0' from the character, then the function can return the value s[0] - '0'.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<iostream>

#include<math.h>

using namespace std;

int string_to_int(string s)

{

// base case

if(s.size() == 1)

{

return s[0] - '0'; // if string is of length 1, return that digit

}

else

{

int n = s.size();

int k = (int)pow(10,n-1);

return (s[0] - '0')*k + string_to_int(s.substr(1,n-1)); // recursion part

}

}

int main()

{

cout << string_to_int("1234") << endl;

}

Add a comment
Know the answer?
Add Answer to:
**C++ only and no vectors or global variables. Thank you, Write a recursive function to convert...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT