-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfDigitOne.java
More file actions
78 lines (66 loc) · 2.01 KB
/
NumberOfDigitOne.java
File metadata and controls
78 lines (66 loc) · 2.01 KB
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
68
69
70
71
72
73
74
75
76
77
78
package leetcode;
import java.util.Stack;
/**
* NumberOfDigitOne
* https://leetcode-cn.com/problems/number-of-digit-one/
* 233. 数字 1 的个数
* https://leetcode-cn.com/problems/number-of-digit-one/solution/lei-ji-ji-suan-ye-you-dong-tai-gui-hua-d-wd71/
* 转移函数比较隐秘, 而且容易出错
*
* @author tobin
* @since 2021-08-13
*/
public class NumberOfDigitOne {
public static void main(String[] args) {
NumberOfDigitOne sol = new NumberOfDigitOne();
// System.out.println(sol.countDigitOne(13));
System.out.println(sol.countDigitOne(10));
System.out.println(sol.countDigitOne(13));
System.out.println(sol.countDigitOne(100));
System.out.println(sol.countDigitOne(113));
System.out.println(sol.countDigitOne(1000));
System.out.println(sol.countDigitOne(1113));
System.out.println(sol.countDigitOne(10000));
}
public int countDigitOne(int n) {
int[] baseCounts = new int[9];
int base = 1;
for (int i = 0; i < 9; i++) {
if (i >= 1) {
baseCounts[i] = base + 10 * baseCounts[i - 1];
} else {
baseCounts[i] = base;
}
base *= 10;
}
int totalOnes = 0;
int tmp = n;
int idx = 0;
int tail = 0;
int accBase = 1;
while (tmp > 0) {
int value = tmp % 10;
int currOnes = 0;
// 每个阶的1
if (idx > 0) {
currOnes = value * baseCounts[idx - 1];
}
// 前缀1
if (value > 1) {
currOnes += accBase;
}
// 尾数处理
if (value == 1) {
currOnes += (1 + tail);
}
currOnes += totalOnes;
// 即结果
totalOnes = currOnes;
tmp /= 10;
idx++;
tail = value * accBase + tail;
accBase *= 10;
}
return totalOnes;
}
}