implement recursive and iterative functions for sum of digits; update VSCode settings
This commit is contained in:
parent
0178845516
commit
410e8d1ac5
2 changed files with 17 additions and 5 deletions
|
|
@ -20,12 +20,21 @@ The sum of digits can be calculated as n mod 10 + sum of digits of n / 10 as lon
|
|||
|
||||
*/
|
||||
|
||||
// TODO: the recursive implementation
|
||||
int sum_of_digits_recursive(int n) {
|
||||
return 0;
|
||||
if (n == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return n % 10 + sum_of_digits_recursive(n / 10);
|
||||
}
|
||||
|
||||
// TODO: the iterative implementation
|
||||
int sum_of_digits_iterative(int n) {
|
||||
return 0;
|
||||
int sum = 0;
|
||||
|
||||
while (n > 0) {
|
||||
sum += n % 10;
|
||||
n = n / 10;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue