FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode/src/main/java/L0233_NumberOfDigitOne.java at master · LjyYano/LeetCode · GitHub
LjyYano
/
LeetCode
Public
Notifications
You must be signed in to change notification settings
Fork
125
Star
342
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode
/
src
/
main
/
java
/
L0233_NumberOfDigitOne.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
67 lines (59 loc) · 2.26 KB
Breadcrumbs
LeetCode
/
src
/
main
/
java
/
L0233_NumberOfDigitOne.java
Copy path
File metadata and controls
67 lines (59 loc) · 2.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* https://leetcode.cn/problems/number-of-digit-one/
*
* 给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
*
* 示例 1:
* 输入:n = 13
* 输出:6
* 解释:数字 1 出现在以下数字中: 1, 10, 11, 12, 13 中(共出现 6 次)
*
* 示例 2:
* 输入:n = 0
* 输出:0
*
* 提示:
* - 0 <= n <= 10⁹
*/
public
class
L0233_NumberOfDigitOne
{
/**
* 计算 1 到 n 中数字 1 出现的次数
* 对于每一位,我们分别计算该位上 1 出现的次数
*/
public
int
countDigitOne
(
int
n
) {
// 记录最终的 1 的个数
int
count
=
0
;
// 从个位开始,依次处理每一位
for
(
long
i
=
1
;
i
<=
n
;
i
*=
10
) {
// 计算当前位的前面的数字和后面的数字
long
prefix
=
n
/ (
i
*
10
);
long
digit
= (
n
/
i
) %
10
;
long
suffix
=
n
%
i
;
// 根据当前位的数字,计算当前位上 1 出现的次数
if
(
digit
==
0
) {
// 如果当前位是 0,那么当前位上 1 出现的次数只由更高位决定
count
+=
prefix
*
i
;
}
else
if
(
digit
==
1
) {
// 如果当前位是 1,那么当前位上 1 出现的次数由更高位和更低位共同决定
count
+=
prefix
*
i
+
suffix
+
1
;
}
else
{
// 如果当前位大于 1,那么当前位上 1 出现的次数由更高位决定,且要加上 i
count
+= (
prefix
+
1
) *
i
;
}
}
return
count
;
}
public
static
void
main
(
String
[]
args
) {
L0233_NumberOfDigitOne
solution
=
new
L0233_NumberOfDigitOne
();
// 测试用例
System
.
out
.
println
(
"Input: n = 13"
);
System
.
out
.
println
(
"Output: "
+
solution
.
countDigitOne
(
13
));
System
.
out
.
println
(
"Expected: 6"
);
System
.
out
.
println
(
"
\n
Input: n = 0"
);
System
.
out
.
println
(
"Output: "
+
solution
.
countDigitOne
(
0
));
System
.
out
.
println
(
"Expected: 0"
);
System
.
out
.
println
(
"
\n
Input: n = 100"
);
System
.
out
.
println
(
"Output: "
+
solution
.
countDigitOne
(
100
));
System
.
out
.
println
(
"Expected: 21"
);
}
}
Back
|
FazBrowse Home
|
New Git URL