Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a7092d3

Browse files
committed
"Number of Digit One"
1 parent 9807459 commit a7092d3

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
8181
| 236 | [Lowest Common Ancestor of a Binary Tree] | [C++](src/236.cpp) |
8282
| 235 | [Lowest Common Ancestor of a Binary Search Tree] | [C](src/235.c) |
8383
| 234 | [Palindrome Linked List] | [C](src/234.c) |
84-
| 233 | [Number of Digit One] | |
84+
| 233 | [Number of Digit One] | [C](src/233.c) |
8585
| 232 | [Implement Queue using Stacks] | [C](src/232.c) |
8686
| 231 | [Power of Two] | [C](src/231.c) |
8787
| 230 | [Kth Smallest Element in a BST] | [C](src/230.c) |

‎src/233.c‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <stdio.h>
2+
#include <assert.h>
3+
4+
int countDigitOne(int n) {
5+
if (n <= 0) return 0;
6+
if (n >= 1 && n <= 9) return 1;
7+
8+
int x = n; /* first digit of n */
9+
int v = 1; /* round value of n that all digits are zero except first digit */
10+
while (x >= 10) {
11+
x /= 10;
12+
v *= 10;
13+
}
14+
15+
if (x != 1) {
16+
return x * countDigitOne(v - 1) + countDigitOne(n % v) + v;
17+
}
18+
else {
19+
return countDigitOne(v - 1) + countDigitOne(n % v) + n % v + 1;
20+
}
21+
}
22+
23+
int main() {
24+
assert(countDigitOne(-1) == 0);
25+
assert(countDigitOne(1) == 1);
26+
assert(countDigitOne(10) == 2);
27+
assert(countDigitOne(13) == 6);
28+
assert(countDigitOne(21) == 13);
29+
assert(countDigitOne(99) == 20);
30+
assert(countDigitOne(115) == 44);
31+
32+
printf("all tests passed!\n");
33+
34+
return 0;
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /