1到n的数字1出现的次数

题目

https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof

解法

解题思路:

将 1 ~ n 的个位、十位、百位、…的 1出现次数相加,即为 1出现的总次数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class SO43_CountDigitOne {
public static void main(String[] args) {

}
public int countDigitOne(int n) {
int digit = 1, res = 0;
int high = n/10, cur = n%10, low = 0;
while (high != 0 || cur !=0) {
if (cur == 0) {
res += high*digit;
} else if(cur == 1) {
res += high*digit+low+1;
} else {
res += (high+1)*digit;
}
low += cur*digit;
cur = high%10;
high /= 10;
digit *= 10;
}
return res;
}

}
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
如果n = 4560234
让我们统计一下千位有多少个 1
xyz 可以取 0 到 455, abc 可以取 0 到 999
4551000 to 4551999 (1000)
4541000 to 4541999 (1000)
4531000 to 4531999 (1000)
...
21000 to 21999 (1000)
11000 to 11999 (1000)
1000 to 1999 (1000)
总共就是 456 * 1000

如果 n = 4561234
xyz 可以取 0 到 455, abc 可以取 0 到 999
4551000 to 4551999 (1000)
4541000 to 4541999 (1000)
4531000 to 4531999 (1000)
...
1000 to 1999 (1000)
xyz 还可以取 456, abc 可以取 0 到 234
4561000 to 4561234 (234 + 1)
总共就是 456 * 1000 + 234 + 1

如果 n = 4563234
xyz 可以取 0 到 455, abc 可以取 0 到 999
4551000 to 4551999 (1000)
4541000 to 4541999 (1000)
4531000 to 4531999 (1000)
...
1000 to 1999 (1000)
xyz 还可以取 456, abc 可以取 0 到 999
4561000 to 4561999 (1000)
总共就是 456 * 1000 + 1000
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×