In: Computer Science
Please write in java: Write a recursive method toNumber that forms the integer sum of all digit characters in a string. For example, the result of toNumber("3ac4") would be 7. Hint: If next is a digit character ('0' through '9'), Character.isDigit(next) is true and the numeric value of next is Character. digit(next, 10).
Java Program :
public class Main
{
// Recursive function toNumber(s)
public static int toNumber(String s)
{
if(s.isEmpty()) // Base case : return 0 if string is empty
{
return 0;
}
else // string is not empty
{
if(Character.isDigit(s.charAt(0))) // check if character is digit from '0' to '9'
{
// subract '0' from digit to convert character to integer digit
return s.charAt(0) - '0' + toNumber(s.substring(1)); // call the recursive function with remaining string
}
else
{
return toNumber(s.substring(1)); // if not a digit then simply call the recursive function again
}
}
}
public static void main(String[] args) {
System.out.println(toNumber("3ac4"));
}
}
Screenshot :