文章
454
粉丝
0
获赞
1
访问
10.5k
给定 n 和数字 k(1≤k≤9),求 1 到 n 的所有十进制表示中数字 k 出现的总次数。
n ≤ 1e6,直接枚举 1..n,把每个数不断取余拆位,遇到 k 就累加。
拆位循环用除以 10 直到 0 的方式,代价是 O(位数)。
累加结果最大约 6e6,用 64 位整数更保险。
O(n log n),空间 O(1)。
C:
#include <stdio.h>
long long cnt(long long n, int d){
long long ans=0, base=1, high, cur, low;
while(n/base>0){
high=n/(base*10);
cur=(n/base)%10;
low=n%base;
if(d!=0){
if(cur>d) ans+=(high+1)*base;
else if(cur==d) ans+=high*base+low+1;
else ans+=high*base;
}else{
if(high==0) break;
if(cur>0) ans+=high*base;
else if(cur==0) ans+=(high-1)*base+low+1;
else ans+=(high-1)*base;
}
if(base>n/10) break;
base*=10;
}
return ans;
}
int main(){
long long n; int d;
while(scanf("%lld%d",&n,&d)==2) printf("%lld\n", cnt(n,d));
return 0;
}
C++:
#include <stdio.h>
long long cnt(long long n, int d)...
登录后发布评论
暂无评论,来抢沙发