Open In App

Convert a String to an Integer using Recursion

Last Updated : 17 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a string str representing a string, the task is to convert the given string into an integer.

Examples:  

Input: str = “1235” 
Output: 1235
Explanation: “1235” is converted to the integer 1235 by extracting and combining its digits.

Input: str = “0145” 
Output: 145  

Approach

To recursively converts a numeric string into an integer. It starts from the first character, extracts its numeric value, and multiplies it by the appropriate power of 10 based on its position. The function then recursively processes the remaining characters until the entire string is converted. A helper function is used to manage the recursive calls, ensuring an efficient conversion process.

C++
#include <bits/stdc++.h>
using namespace std;

int stringToIntHelper(const string &str, int index) {
    
    // Base case: when index reaches the end of the string
    if (index == str.length()) 
        return 0;

    // Convert current character to digit
    int digit = str[index] - '0';

    // Recursively compute the rest of the number
    return digit * pow(10, str.length() - index - 1) + stringToIntHelper(str, index + 1);
}

// Wrapper function
int stringToInt(string str) {
    return stringToIntHelper(str, 0);
}

// Driver code
int main() {
    string str = "1235";
    cout << stringToInt(str) << endl;
    return 0;
}
Java Python C# JavaScript

Output
1235

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), due to recursive function calls stored in the call stack.




Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg