233. 数字 1 的个数
https://leetcode-cn.com/problems/number-of-digit-one/

这题同时也是:
《剑指Offer 第二版》第43题
这题有个最简单的暴力的解法,就是遍历每个数字,然后再遍历每个数字的,如果是1就进行累加。但是这样的时间复杂度太高了,这样我们就要用分段的思想来解决这个问题,再说思想的是,我们先来看看几个例子,来看看分段思想是如何解决这个问题的。



比如21345 这个,首先分成第一段,1 ~ 1345和第二段1346 ~ 21345,这样基本上就是完成了第一次分段,因为万位上面有肯定有1,在10000 ~ 19999这个区间有10000个1,我们先记住这个,那么其他位置上呢?因为后面的每个位置上都会出现1的情况,比如千位上是1,那么百,十,个位都可以0~9的任何数字,就是10 * 10 * 10,那么就是肯定就是四个位置上都可以是1,那么就是4 * 10 * 10 * 10,所以这里就是第二段 1346~21345 数字就的就有18000个1。接下来可以继续分解。
但是有一点需要注意,只有当万位上大于等于2的时候,万位上的才有10000个1,如果小于2,是1,那么1的数量就是后面的1345+1个。

show the code
class Solution {
public int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
String stringN = n + "";
int ans = 0;
while (!stringN.isEmpty()) {
int tempLen = stringN.length();
String firstChar = stringN.charAt(0) + "";
if (Integer.parseInt(firstChar) >= 2) {
ans += 1 * Math.pow(10, tempLen - 1);
} else if (firstChar.equals("1")) {
if ("".equals(stringN.substring(1, tempLen))) {
ans += 1;
} else if (!"".equals(stringN.substring(1, tempLen))){
ans += Integer.parseInt(stringN.substring(1, tempLen)) + 1;
}
}
if (tempLen > 1) {
ans += Integer.parseInt(firstChar) * (tempLen - 1) * Math.pow(10, tempLen - 2);
}
stringN = stringN.substring(1);
}
return ans;
}
}
以上的时间复杂度就是 O ( l o g 10 ( n ) ) O(log10(n)) O(log10(n))
本文详细解析了LeetCode 233题“数字1的个数”的高效算法,通过分段思想降低时间复杂度至O(log10(n)),并提供了实现代码。
1053

被折叠的 条评论
为什么被折叠?



