I'm extremely new to the whole idea of recursion, and it's blowing my mind a bit to be honest. I'm trying to turn this function I wrote into a recursive one...
public static int to_number(String s)
{
int total = 0;
int n=s.length();
for(int i = 0 ; i < n ; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)){
int value=Character.getNumericValue(c);
total +=value;
}
}
System.out.println(total);
return total;
}
It reads in a string, such as "3aaa6a3", iterates through the string, if the char is a digit, it adds it to total, and so on. What I have so far...
public static int to_number(String s)
{
int total = 0;
int n=s.length();
int i=0;
if (i == n){
return 0; //if gone through the whole string
}
char c = s.charAt(i);
if (Character.isDigit(c)){
int value=Character.getNumericValue(c);
total +=value;
}
System.out.println(total);
i++;
to_number(); //trying to call the same function
return total;
}
I feel like I'm close, but just not getting it. Thanks for your time and effort!
to_number(String)method with no parameters.swill cause infinite recursion. The OP needs to pass a substring ofs.if ( i == n)will make sense. You should be able to proceed with this tip