【发布时间】:2019-07-09 16:09:45
【问题描述】:
数字字母计数 问题 17 如果将数字 1 到 5 写成单词:一、二、三、四、五,那么总共使用了 3 + 3 + 5 + 4 + 4 = 19 个字母。
如果从 1 到 1000(包括一千)的所有数字都用文字写出来,会使用多少个字母?
注意:不要计算空格或连字符。例如,342(342)包含 23 个字母,115(115)包含 20 个字母。写出数字时使用“and”符合英国用法。
尝试将一些数字与它们都匹配的字符串进行比较。
using System;
using System.Collections.Generic;
public class Program
{
static int n = 1000;
static List<int> letterCountCache = new List<int>();
public static void Main()
{
long t = 0;
letterCountCache.Add(0);
for (int i = 1; i <= n; i ++)
{
letterCountCache.Add(GetLetterCount(i));
t += letterCountCache[i];
}
Console.WriteLine(t);
Console.WriteLine(letterCountCache[70] + " " + "seventy".Length);
}
static int GetLetterCount(int i)
{
if (letterCountCache.Count > i)
return letterCountCache[i];
switch (i)
{
case 1:
return "one".Length;
case 2:
return "two".Length;
case 3:
return "three".Length;
case 4:
return "four".Length;
case 5:
return "five".Length;
case 6:
return "six".Length;
case 7:
return "seven".Length;
case 8:
return "eight".Length;
case 9:
return "nine".Length;
case 10:
return "ten".Length;
case 11:
return "eleven".Length;
case 12:
return "twelve".Length;
case 13:
return "thirteen".Length;
case 14:
return "fourteen".Length;
case 15:
return "fifteen".Length;
case 16:
return "sixteen".Length;
case 17:
return "seventeen".Length;
case 18:
return "eighteen".Length;
case 19:
return "nineteen".Length;
}
if (i >=20 && i <=29)
return "twenty".Length + GetLetterCount(i % 10);
if (i >=30 && i <=39)
return "thirty".Length + GetLetterCount(i % 10);
if (i >= 40 && i <= 49)
return "forty".Length + GetLetterCount(i % 10);
if (i >=50 && i <= 59)
return "fifty".Length + GetLetterCount(i % 10);
if (i > 80 && i < 89)
return "eighty".Length + GetLetterCount(i % 10);
if (i >= 60 && i <= 99)
return GetLetterCount(i % 10) + "ty".Length + GetLetterCount(i / 10);
if (i == 1000)
return "onethousand".Length;
if (i % 100 == 0)
return GetLetterCount(i / 100) + "hundred".Length;
return GetLetterCount(i / 100) + "hundred".Length + "and".Length + GetLetterCount(i % 100);
}
}
正确的结果显然是 21124。我的返回 21144。有人知道为什么吗?
【问题讨论】:
-
我猜这是你循环中的停止条件。
-
"onethousand"不应该是两个字吗?"one thousand" -
@DmitryBychenko 他删除了空间,所以他不必计算它。就像任何连字符一样。
-
你没有返回 0 的 string.empty.length
-
@DanielBrughera 发现了这一点,但它从未发生过,因为它被顶部的“缓存”捕获,在方法运行之前为索引 0 添加了一个零条目。
标签: c#