-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_digits.cpp
More file actions
47 lines (33 loc) · 801 Bytes
/
add_digits.cpp
File metadata and controls
47 lines (33 loc) · 801 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Problem: Add digits
(https://leetcode.com/problems/add-digits/)
The digital root is the single-digit sum of the iterative process of adding
up all the digits of a non-negative integer.
Let n be a non-negative integer with m digits. Let d be the digital root of n.
Theorem: The digital root of n is
d = {
9 if n mod 9 == 0 && n != 0,
n mod 9 otherwise
}
Let's look at d for some n according to the iterative process:
Let n = 0, d = 0
n = 1, d = 1
...
n = 8, d = 8
n = 9, d = 9
n = 10,d = 1
...
n = 19, d = 1
It should be clear from the above that the digital root, from n > 0, is
repeating in a cycle of 1-9.
*/
#include <iostream>
using namespace std;
int addDigits(int num) {
if (num % 9 == 0 && num != 0) {
return 9;
}
return num % 9;
}
int main() {
}