Recursive function that sums the odd digits of an integer
For instance n = 8135267 => 16 Here is a solution but I don't understand it.
int sumOddDigits(int n) {
if(n == 0)
return 0;
if(n%2 == 1) //if n is odd
//returns last digi开发者_JS百科t of n + sumOddDigits(n/10) => n/10 removes the last digit of n
return n % 10 + sumOddDigits(n/10)
else
return sumOddDigits(n/10);
}
Integer divison by ten "cuts off" the last digit: I.e. 1234/10
results in 123
.
Modulo 10 returns the last digit: i.e. 1234%10
results in 4
.
Thus, the above code considers always the last digit. If the last digit is odd (hence the %2==1
stuff) it will be counted, otherwise not. So, if it should count the digit, it takes the last digit (the % 10
-stuff) and continues computing with the remaining digits (the recursion with the /10
-stuff) and adding them to the digit. If the current digit shall not be counted, it continues just with the remaining digits (thus the recursion and the /10
-stuff) without adding it to the current digit.
If the argument is 0, this means that the whole number is traversed, thus the function terminates with returning 0.
% is the modulo operator. It basically finds the remainder of dividing by a number.
n %2 n is only 1 if it's odd. % 10 gets the remainder of the dividing the number by 10, this gets you the currently last digit. Integer division by 10 gets you the next digit as the current last digit (1567/10 = 156)
Think about it this way: Starting with your known answer of 8135267 => 16
, if I asked you for the sum of the odd digits in *3*8135267, what would you do? What if I asked for *4*8135267? How do your manual steps related to that function?
Think of it this way. If you get an even digit your function returns it + function value of the number without that digit. Otherwise it returns the function value of the number without the last digit. On your example:
813526(7) -> 0 + sumEvenDigits(813526)
6 + sumEvenDigits(81352)
2 + sumEvenDigits(8135)
....
8 + sumEvenDigits(0)
0 = 16
Hope this helps.
int sum_odd_digits(int n)
{
int s=0,r=0;
if(n==0)
return 0;
r = n%10;
if(r%2==1)
s = s+r;
n=n/10;
return s+ sum_odd_digits(n);
}
精彩评论