首页 技术 正文
技术 2022年11月9日
0 收藏 671 点赞 2,555 浏览 1094 个字

题意:给定一个数n,问从1到n中,0~9这10个数字分别出现了多少次。比如366这个数,3出现了1次,6出现了2次。

题解:《剑指offer》P174;《编程之美》P132 都给出了统计数字1的O(log(n))的解法。把他们进行改进就得到了这个问题的答案。

下面这个代码是我改的剑指offer的,也有类似编程之美的:传送门

//《剑指offer》P174
#include <bits/stdc++.h>
using namespace std;
int pow1(int n,int len)//注意算的时候不要用math里的pow 会产生误差
{
int ans=;
while(len--) ans*=n;
return ans;
}
int cal(char *c,int i)
{
int len=strlen(c);
int f=*c-'',g=*(c+)-'';
if(len==&&(f<i||i==)) return ;
if(len==&&f>=i) return ;
int a1=,a2=,a3=;
if(i==||f<i) a1=;
else if(f>i) a1=pow1(,len-);
else if(f==i) a1=atoi(c+)+;
a2=f*(len-)*pow1(,len-);
if(g==&&i==) a2=a2-pow1(,len-)+atoi(c+)+;
a3=cal(c+,i);
return a1+a2+a3;
}
int solve(int n,int i)
{
char c[];
sprintf(c,"%d",n);
return cal(c,i);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
for(int i=;i<;i++)
printf("%d%c",solve(n,i),i==?'\n':' ');
}
return ;
}

官方标程:

#include <bits/stdc++.h>using namespace std;vector<int> solve(int n) {
vector<int> res(, );
if(!n) return res;
if(n % < ) {
res = solve(n - );
while(n) {
res[n % ]++;
n /= ;
}
return res;
}
res = solve(n / );
for(int i = ; i < ; i++) res[i] = res[i] * + n / + (i > );
return res;
}
int main() {
int n;
cin >> n;
vector<int> ans = solve(n);
for(int i = ; i < ans.size(); i++) {
i == ? cout << ans[i] : cout << " " << ans[i];
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905