Coders Packet

Creating a Recursive function to convert a given string into Number in Java.

By Jasdeep Singh

We will be writing a java code that will take input as a numeric string that contains only numbers, will be converting the string into corresponding integer and then return the number.

Understanding The Problem

There are two ways of solving this approach either iterative or reccursive.We will be discussing reccursive approach for now in this approach the first thing we will check is whether our string is empty. If it is, we can return 0. If not, then we do some work. To approach  this problem recursively, we will split this string in two parts, one of which will be a single character and the other will be the rest of the string. After spliting the string we will now be passing into recurssive function.

Code

public class solution {
 
  public static int convertStringToInt(String input) {
    if(input.length() == 1) {
      return input.charAt(0) - '0';
      
    }
    int smallOutput = convertStringToInt(input.substring(0, input.length() -1));
    int lastDigit = input.charAt(input.length()-1) - '0';
    return smallOutput*10 + lastDigit;
  }
}
  

 

Download Complete Code

Comments

No comments yet