Recursion-Convert String to Integer

 Take as input str, a number in form of a string. Write a recursive function to convert the number in string form to number in integer form. E.g. for “1234” return 1234. Print the value returned.

Input Format

Enter a number in form of a String

Constraints

1 <= Length of String <= 10

Output Format

Print the number after converting it into integer

Sample Input
1234
Sample Output
1234
Explanation

Convert the string to int. Do not use any inbuilt functions.

import java.util.Scanner;

public class StringToInteger {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String inputNumber = s.next();
System.out.print(strToInt(inputNumber, 0, 0));
s.close();
}

private static int strToInt(String inputNumber, int i, int num) {
if (i == inputNumber.length()) {
return num;
}
num = num * 10 + ((int) inputNumber.charAt(i) - 48);
return strToInt(inputNumber, i + 1, num);
}

}

Post a Comment

0 Comments