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 c7e3bb2

Browse files
author
openset
committed
Add: Number of Digit One
1 parent 7a6932f commit c7e3bb2

File tree

2 files changed

+81
-2
lines changed

2 files changed

+81
-2
lines changed
Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,14 @@
1-
package number_of_digit_one
1+
package problem_233
2+
3+
func countDigitOne(n int) int {
4+
ans, b, x := 0, 1, 0
5+
for b <= n {
6+
x = n / b
7+
ans += (x + 8) / 10 * b
8+
if x%10 == 1 {
9+
ans += n%b + 1
10+
}
11+
b *= 10
12+
}
13+
return ans
14+
}
Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,67 @@
1-
package number_of_digit_one
1+
package problem_233
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input int
7+
expected int
8+
}
9+
10+
func TestCountDigitOne(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: 0,
14+
expected: 0,
15+
},
16+
{
17+
input: 1,
18+
expected: 1,
19+
},
20+
{
21+
input: 12,
22+
expected: 5,
23+
},
24+
{
25+
input: 99,
26+
expected: 20,
27+
},
28+
{
29+
input: 100,
30+
expected: 21,
31+
},
32+
{
33+
input: 123,
34+
expected: 57,
35+
},
36+
{
37+
input: 1234,
38+
expected: 689,
39+
},
40+
{
41+
input: 12345,
42+
expected: 8121,
43+
},
44+
{
45+
input: 123456,
46+
expected: 93553,
47+
},
48+
{
49+
input: 1234567,
50+
expected: 1058985,
51+
},
52+
{
53+
input: 12345678,
54+
expected: 11824417,
55+
},
56+
{
57+
input: 123456789,
58+
expected: 130589849,
59+
},
60+
}
61+
for _, tc := range tests {
62+
output := countDigitOne(tc.input)
63+
if output != tc.expected {
64+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
65+
}
66+
}
67+
}

0 commit comments

Comments
(0)

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