f(n) = n

题目: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的时间。为了不影响大家的思路,我最后贴上我的程序。

语言不限,随便了。

这里我只用程序逻列了所有f(n) = n时n的值
程序如下:

///jailusd@hotmail.com
///2006-09-09


/*
 * 题目:;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的时间。为了不影响大家的思路,我最后贴上我的程序。

语言不限,随便了。
 
*/


using System;
using System.Collections.Generic;
using System.Text;

namespace ping4210_1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            Count();

            Console.ReadLine();
        }


        
static void Count()
        
{
            
long N = 1;
            
bool bl = true;
            
int intCount = 0;

            
int intTemp = 0;

            
//核心代码
            while (bl)
            
{
                intTemp 
= 0;
                
char[] chara = N.ToString().ToCharArray();

                
for (int i = 0; i < chara.Length; i++)
                
{
                    
if (chara[i] == '1')
                    
{
                        intTemp
++;
                    }

                }


                intCount 
+= intTemp;

                
if (intCount == N)
                
{
                    Console.WriteLine(N.ToString());
                }


                N
++;

                
//为防止溢止设为N == long.MaxValue
                if (N == long.MaxValue)
                
{
                    bl 
= false;
                }

            }


            Console.WriteLine(
"运行结束!");
            Console.WriteLine();
        }

    }

}


以下是部分运行结果:
1
199981
199982
199983
199984
199985
199986
199987
199988
199989
199990
200000
200001
1599981
1599982
1599983
1599984
1599985
1599986
1599987
1599988
1599989
1599990
2600000
2600001
13199998
35000000
35000001
35199981
35199982
35199983
35199984
35199985
35199986
35199987
35199988
35199989
35199990
35200000
35200001
117463825
posted @ 2006-09-09 20:06  Jailu  阅读(1095)  评论(2编辑  收藏  举报