diff options
Diffstat (limited to 'add_digits.c')
-rw-r--r-- | add_digits.c | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/add_digits.c b/add_digits.c new file mode 100644 index 0000000..c887a06 --- /dev/null +++ b/add_digits.c @@ -0,0 +1,22 @@ +// 258. Add Digits +#include <stdio.h> + +// given an integer 'num', repeatedly add all its digits until +// the result has onlye one digit and return it + +int addDigits(int num) { + int sum = 0; + while (num) { + sum += num % 10; + num /= 10; + } + if (sum < 10) + return sum; + else + return addDigits(sum); +} + +int main() { + printf("%d\n", addDigits(38)); // expect: 2 + printf("%d\n", addDigits(0)); // expect: 0 +} |