Google面试题 & 一位牛人写的程序

用了递归,但速度还是不错,呵呵...,有时候是10ms之内

#include "stdafx.h"

#include <windows.h>
#include <stdlib.h>

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;

/*if(argc>1)
{
n = atoi(argv[1]);
ncount = f(n);
printf("f(%d) = %d/n",n,ncount);
}*/

int beginTime=GetTickCount();
//init gTable
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);
}

int endTime=GetTickCount();
endTime-=beginTime;

printf("time: %d ms/n",endTime);
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);
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值