Convert a String to an Integer using Recursion
Last Updated :
04 Jun, 2022
Given a string str representing a string, the task is to convert the given string into an integer.
Examples:
Input: str = “1234”
Output: 1234
Input: str = “0145”
Output: 145
Approach: Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of 10 and then add the recursive result for the substring starting at the second index. The termination condition will be when the passed string consists of a single digit. In that case, return the digit represented by the string.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int stringToInt(string str)
{
if (str.length() == 1)
return (str[0] - '0' );
double y = stringToInt(str.substr(1));
double x = str[0] - '0' ;
x = x * pow (10, str.length() - 1) + y;
return int (x);
}
int main()
{
string str = "1235" ;
cout << (stringToInt(str)) << endl;
}
|
Java
public class GFG {
static int stringToInt(String str)
{
if (str.length() == 1 )
return (str.charAt( 0 ) - '0' );
double y = stringToInt(str.substring( 1 ));
double x = str.charAt( 0 ) - '0' ;
x = x * Math.pow( 10 , str.length() - 1 ) + y;
return ( int )(x);
}
public static void main(String[] args)
{
String str = "1235" ;
System.out.print(stringToInt(str));
}
}
|
Python3
def stringToInt( str ):
if ( len ( str ) = = 1 ):
return ord ( str [ 0 ]) - ord ( '0' )
y = stringToInt( str [ 1 :])
x = ord ( str [ 0 ]) - ord ( '0' )
x = x * ( 10 * * ( len ( str ) - 1 )) + y
return x
str = "1235"
print (stringToInt( str ))
|
C#
using System;
class GFG
{
static int stringToInt(String str)
{
if (str.Length == 1)
return (str[0] - '0' );
double y = stringToInt(str.Substring(1));
double x = str[0] - '0' ;
x = x * Math.Pow(10, str.Length - 1) + y;
return ( int )(x);
}
public static void Main(String[] args)
{
String str = "1235" ;
Console.Write(stringToInt(str));
}
}
|
Javascript
<script>
function stringToInt(str)
{
if (str.length == 1)
return (str[0] - '0' );
var y = stringToInt(str.substring(1));
var x = str[0] - '0' ;
x = x * Math.pow(10, str.Length - 1) + y;
return (x);
}
var str = "1235" .split()
document.write(stringToInt(str));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...