I am creating two methods - one that calculates the sum of the digits in a number recursively, and the other iteratively.
I have created the recursive method, and for the most part I understand the concept of finding the sum of digits, but I am not sure how to correctly put it into an iterative method. My code does not give me the correct output.
public static int iterativeDigitSum(long n) {
if(n < 0){
String err = "n must be positive. n = " + n;
throw new IllegalArgumentException(err);
}
if(n == 0){
return 0;
}
long sum = 0;
long i = 0;
while(n > 0){
i = n % 10;
sum = sum + n;
n = n / 10;
}
int inSum = (int)sum;
return inSum;
}
The number "n" is 10, meaning the expected output is 1. I am getting 11. Could you please explain to me what I am doing wrong, and possibly how to fix it? Thank you so much.