Reputation: 223
I have the following code that takes a string (of digits) and turns it into an integer value. But instead the integer output is in reverse. For example, if you type in 5999, you get 9995 in return. What am I doing incorrectly?
int stringToInt(string myString, int m) {
if (m == ((int)myString.length()-1))
return (myString[m]-48);
else
return (10*(stringToInt(myString, m+1)) + (myString[m]-48));
}
Upvotes: 0
Views: 83
Reputation: 7929
Because in numerical notation, digit order decreases from left to right, you need to start recursion by the end of the string (lowest order digit). You can give initial m
as myString.size()-1
and go in reverse way:
int stringToInt(string myString, int m) {
if (m == 0)
return (myString[m]-48);
else
return (10*(stringToInt(myString, m-1)) + (myString[m]-48));
}
Upvotes: 2