Sign-up....

google的一道面世题,算法高手进来看看

这个题目的英文原题是:

Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n.

For example, f(13)=6. Notice that f(1)=1. What is the next largest n such that f(n)=n?

翻译过来大体是这样:

有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数。比如f(13)=6,现在f(1)=1,问下一个最大的f(n)=n的n是什么?

为什么f(13)=6, 因为1,2,3,4,5,6,7,8,9,10,11,12,13.数数1的个数,正好是6.

请大家写出自己的算法,并统计一些在你机器上计算出1111111110的时间。为了不影响大家的思路,我最后贴上我的程序。

语言不限,随便了。

[605 byte] By [1234567] at [2007-8-15 11:11:23]
# 1 Re: google的一道面世题,算法高手进来看看
应该先用数学方法得出公式,写程序就简单了
ASP深着那 at 2007-3-26 19:40:35 >
# 2 Re: google的一道面世题,算法高手进来看看
是这个意思,求的是f(n)=n的n.

比如f(199981)=199981,要求找出这个199981来。

★seraph★ at 2007-3-26 19:40:45 >
# 3 Re: google的一道面世题,算法高手进来看看
首先,确定最大的数。我们通过统计可以知道,9以下为:1个,99以下为:1*10+10*1=20个,999以下为:1*100+10*20=300个.n位数位n*100000(n-1个0)+10*(n-1位时的个数)。

得到最大位数为10.

然后,计算首位,当首位为1、2...,直到出现一个n,当首位为n时1个数小于n000000000,当为n+1时,1的个数大于(n+1)000000000,然后就这样推出整个数。

Tasting BREW... at 2007-3-26 19:40:50 >
# 4 Re: google的一道面世题,算法高手进来看看
if( (ntemp%10) <= 1 )

{

ret -= i;

}

改成if( (ntemp%10) == 1 )

{

ret -= i;

}

SongZip at 2007-3-26 19:41:5 >
# 5 Re: google的一道面世题,算法高手进来看看
f(10^n - 1) = 10^(n-1) + f(10^(n-1)) * 10

f(9) = 1

f(99) = 20

f(999) = 300

f(9999) = 4000

f(99999) = 50000

就是最高为加1再乘以10

如果f(m)中m != 10^n - 1,则可以分解再做

无心阁 at 2007-3-26 19:42:29 >
# 6 Re: google的一道面世题,算法高手进来看看
我觉得

先找到一个与n最近的数nx满足条件f(nx)=nx;

以这个数为起点计算比较快.因为f(nx)=nx中的nx是比较容易计算的。若从1可是计算,对于比较大的数就很费事

anonymous at 2007-3-30 17:5:3 >
# 7 Re: google的一道面世题,算法高手进来看看
nx是所有位都为 1的数如1,11,111,1111,11111,111111
anonymous at 2007-3-30 17:9:49 >
# 8 Re: google的一道面世题,算法高手进来看看
实际上

计算f(nx)的思想与nx的排列组合的思想是一致的

所以,可以用算术公式计算

anonymous at 2007-3-30 17:21:25 >
# 9 Re: google的一道面世题,算法高手进来看看
不好意思,是与nx中1的个数的排列组合一致
anonymous at 2007-3-30 17:22:28 >
# 10 Re: google的一道面世题,算法高手进来看看
f(1111111110)自然很好算了

f(1111111110)=f(1111111111)-11;

anonymous at 2007-3-30 17:24:29 >
# 11 Re: google的一道面世题,算法高手进来看看
f(1111111110)=f(1111111111-1)=f(1111111111)-10;
anonymous at 2007-3-30 17:26:2 >
# 12 Re: google的一道面世题,算法高手进来看看
楼上的聪敏....
狗狗 at 2007-3-30 22:27:48 >

C/C++

All Classified