Skip to content

Instantly share code, notes, and snippets.

@tomfuru
Created August 8, 2012 06:07
Show Gist options
  • Save tomfuru/3292658 to your computer and use it in GitHub Desktop.
Save tomfuru/3292658 to your computer and use it in GitHub Desktop.
dc201208078
using System;
using System.Collections;
using System.Linq;
namespace Application
{
class MainClass
{
/*
* 1 から 5 までの数字を英単語で書けば one, two, three, four, five であり、全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている。
* では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば、全部で何文字になるか。
* 注: 空白文字やハイフンを数えないこと。例えば、342 (three hundred and forty-two) は 23 文字、115 (one hundred and fifteen) は20文字と数える。なお、"and" を使用するのは英国の慣習。
*/
public static void Main(string[] args)
{
Console.WriteLine(Enumerable.Range(1, 1000).Aggregate(0, (ag, val) => AlphaNum(val) + ag));
}
private static int AlphaNum(int num)
{
if (num >= 1 && num < 20) {
return ONE_TO_NINETEEN[num];
} else if (num >= 20 && num < 100) {
return TWENTY_TO_NINETY[num / 10] + ((num % 10 == 0) ? 0 : AlphaNum(num % 10));
} else if (num >= 100 && num < 1000) {
return ONE_TO_NINETEEN[num / 100] + HUNDRED + ((num % 100 == 0) ? 0 : (AND + AlphaNum(num % 100)));
} else if (num == 1000) {
return ONE_TO_NINETEEN[1] + THOUSAND;
} else { throw new NotSupportedException(); }
}
private static readonly int[] ONE_TO_NINETEEN = { -1, // dummy
"ONE".Length, "TWO".Length, "THREE".Length, "FOUR".Length,
"FIVE".Length, "SIX".Length, "SEVEN".Length, "EIGHT".Length,
"NINE".Length, "TEN".Length, "ELEVEN".Length, "TWELVE".Length,
"THIRTEEN".Length, "FOURTEEN".Length, "FIFTEEN".Length, "SIXTEEN".Length,
"SEVENTEEN".Length, "EIGHTEEN".Length, "NINETEEN".Length
};
private static readonly int[] TWENTY_TO_NINETY = { -1, -1, // dummy
"TWENTY".Length, "THIRTY".Length, "FORTY".Length,
"FIFTY".Length, "SIXTY".Length, "SEVENTY".Length,
"EIGHTY".Length, "NINETY".Length
};
private static readonly int HUNDRED = "HUNDRED".Length;
private static readonly int THOUSAND = "THOUSAND".Length;
private static readonly int AND = "AND".Length;
}
}
// 21124
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment