首页 > 解决方案 > 为了给书页编号,使用了 n 位数字。找出书中的页数

问题描述

我试着这样做,但这个算法很慢。1 <= n <= 10^9,所以 n 非常大!程序不能再工作 1 秒

using System;

struct MainStruct
{
    private static void Main ()
    {
        int n = int.Parse (Console.ReadLine ());
        int page = 1, count = 0;
        while (true) {
            count = count + page.ToString ().Length;
            if (count == n) {
                break;
            }
            page = page + 1;
        }

        Console.WriteLine (page);
    }
}

标签: c#algorithm

解决方案


string NumberOfPages(int numberOfDigits)
{
    return "Between " +
        Convert.ToInt32(Math.Pow(10, numberOfDigits - 1)).ToString()
        + " and " +
        Convert.ToInt32(Math.Pow(10, numberOfDigits) - 1).ToString();
}

10 到 99 之间的任何数字都需要 2 位数字,即 10^1 和 10^2-1。等等。


推荐阅读