So I have a question that asks me to write a method that is passed a String consisting of digits, and this method should return the sum of those digits. So if the String is "123" my method should return the value 6. If the null String is passed, my method should return zero. It asks me to use Recursion. Here's what I have so far:
public class Q2 {
public static void main(String[] args) {
String s = "135";
System.out.println(sumDig(s));
}
public static String sumDig(int num)
{
int i = Integer.parseInt(num);
int sum = 0;
if (i == 0)
return sum;
int sum = num%10 + sumDig(num/10);
return sum;
}
}
I'm just having a bit of trouble trying to see if I'm on the right track, I know it's totally wonky and recursion is still really odd to me so any help is really appreciated. Thank you!
Edit: I don't think this is a duplicate of any other problems asking how to find sum of digits using recursion, this is very similar but it's different because it asks to find sum of digits from a String.