Skip to content

Instantly share code, notes, and snippets.

@vannjot
Created March 10, 2017 01:42
Show Gist options
  • Save vannjot/054259b05098f4086bd796ce9340277f to your computer and use it in GitHub Desktop.
Save vannjot/054259b05098f4086bd796ce9340277f to your computer and use it in GitHub Desktop.
Recursion Assignment 2 StringToInteger
/*
Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
Input format : Numeric string (string, Eg. "1234")
Output format : Corresponding integer (int, Eg. 1234)
*/
public static int convertStringToInt(String input){
if(input.length()<1)
{
return 0;
}
return input.charAt(input.length()-1)-'0'+(10*convertStringToInt(input.substring(0,input.length()-1)));
}
/*
Working
3+10*
2+10*
1+10*
0 //fall back of recursive calls
1+10*0 =1
2+10*1 =12
3+10*12 =123
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment