求从1到N中1的出现的数目



在很多书上都看到这个算法问题:


给定一个十进制正整数N, 写下从1开始,到N的所有整数,然后数一下其中出现所有“1”的个数,即求f(N)。


例如:
N=2, 写下1,2,。 出现1个1;
N=13, 我们写下:1,2,3,4,5,6,7,8,9,10,11,12,13,出现1个的个数是6.


求解f(N)=N 的最大值?


问题分解:


1. 首先求解函数f(N),即饭后1 到N之间出现的 1 的个数,如f(13)=6


2  在求满足条件的 f(N)=N 的最大值?


下面是一种求解方法:



#include<stdlib.h>
#include<iostream>
using namespace std;
int f(int n);
int count1(int n);
int cal(unsigned int number, int nwei, int count1,unsigned int ncount);

int gTable[10];
const unsigned int gMAX = 4000000000L;

int main(int argc, char * argv[])
{
int i;
unsigned int n=1;
unsigned int ncount = 0;
int nwei = 0;
int ncount1;

for(i=0;i<10;++i)
{
n*=10;
gTable[i]=f(n-1);
}

n=0;
nwei=0;
ncount1=0;

while(n<gMAX)
{
unsigned int temp;

temp = 1;

ncount =cal(n,nwei, ncount1, ncount);
for(i=0;i<nwei;++i)
	temp*=10;
n+=temp;
if((n/temp)/10==1) ++nwei;
ncount1=count1(n);

}



return 0;

}


/*                        */

int f(int n)
{
int ret = 0;
int ntemp=n;
int ntemp2=1;
int i=1;
while(ntemp)
{
ret +=(((ntemp-1)/10)+1)*i;
if((ntemp%10)==1)
{
ret ==i;
ret+=ntemp2;
}
ntemp=ntemp/10;
i*=10;
ntemp2 = n%i+1;


}
return ret;

}
 

/*                       */
int count1(int n)
{

int count=0;
while(n)
{
if((n%10)==1)
	++count;
n/=10;

}
return count;
}


/*                         */
int cal(unsigned int number, int nwei, int count1,unsigned int ncount)
{
int i,n=1;
unsigned int maxcount;
if(nwei ==0)
{
ncount+=count1;
if(number == ncount)
{
printf("f(%d) = %d\n", number, number);
}
return ncount;

}

for(i=0;i<nwei;++i)
	n*=10;
maxcount=ncount+gTable[nwei-1];
maxcount+=count1*n;
if(ncount>(number+(n-1)))
{return maxcount;}

if(maxcount < number)
{
return maxcount;

}

n/=10;
for(i=0;i<10;++i)
{
if(i==1)
	ncount=cal(number+i*n,nwei-1,count1+1,ncount);
else
	ncount=cal(number+i*n,nwei-1,count1,ncount);



}
return ncount;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值