c# - 为了给书页编号,使用了 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);
}
}
解决方案
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。等等。
推荐阅读
- dataframe - Pyspark 有条件的累积和
- sql - 我们可以在Oracle中向表中添加列的同时插入行吗
- html - 防止图像与表格的边框重叠?
- angular - TypeScript/TSLint:TSLint 无法通过 baseUrl 识别根相对导入
- android - 安卓。在设备关闭时显示全屏内容(活动?!)
- php - 从路径显示图像返回 about:Blank
- django - 如何在 django 中获取相关集(多对多字段)
- python-3.x - df.apply(lambda x: x.value_counts()) 的矢量化版本
- c# - 逗号分隔的模型绑定
- sql - 布尔值是否大于 x?