输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
自我解(动态规划,时间复杂度为O(n),超时)
class Solution {
public int countDigitOne(int n) {
int num = 0;
for(int i = 1 ; i <= n ; i ++){
int a = i;
while(a!=0){
if(a%10==1)
num++;
a/=10;
}
}
return num;
}
}
官方解(逐位计算,时间复杂度为O(logn))
class Solution {
public int countDigitOne(int n) {
int result = 0,digit = 1;
int high = n/10,cur = n%10,low = 0;
while(high!=0||cur!=0){
if(cur==0)result+=high*digit;
else if(cur==1)result+=high*digit+low+1;
else result+=(high+1)*digit;
low += cur*digit;
cur = high%10;
high = high/10;
digit*=10;
}
return result;
}
}