Skip to content

Commit 7ea5439

Browse files
committed
"Add Digits"
1 parent 0581cad commit 7ea5439

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
3131
| 261 | [Graph Valid Tree]| |
3232
| 260 | [Single Number III] | |
3333
| 259 | [3Sum Smaller]| |
34-
| 258 | [Add Digits] | |
34+
| 258 | [Add Digits] | [C](src/258.c) |
3535
| 257 | [Binary Tree Paths] | |
3636
| 256 | [Paint House]| |
3737
| 255 | [Verify Preorder Sequence in Binary Search Tree]| |

src/258.c

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <stdio.h>
2+
#include <assert.h>
3+
4+
int addDigits0(int num) {
5+
int ans = 0;
6+
while (num > 0) {
7+
ans += num % 10;
8+
num /= 10;
9+
if (ans >= 10) {
10+
ans = ans / 10 + ans % 10;
11+
}
12+
}
13+
return ans;
14+
}
15+
16+
int addDigits(int num) {
17+
return 1 + (num - 1) % 9;
18+
}
19+
20+
int main() {
21+
22+
assert(addDigits(0) == 0);
23+
assert(addDigits(1) == 1);
24+
assert(addDigits(9) == 9);
25+
assert(addDigits(38) == 2);
26+
assert(addDigits(12345) == 6);
27+
28+
printf("all tests passed!\n");
29+
30+
return 0;
31+
}

0 commit comments

Comments
 (0)