如果用英文写出数字1到5: one, two, three, four, five, 那么一共需要3 + 3 + 5 + 4 + 4 = 19个字母。
如果数字1到1000(包含1000)用英文写出,那么一共需要多少个字母?
注意: 空格和连字符不算在内。例如,342 (three hundred and forty-two)包含23个字母; 115 (one hundred and fifteen)包含20个字母。"and" 的使用与英国标准一致。
public class Problem17
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
howmany();
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}
static void howmany()
{
//zero one, two, three, four, five, six seven eight nine ten
//eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen
//nineteen twenty thirty forty fifty sixty seventy eighty ninety
int array[] = {0,3,3,5,4,4,3,5,5,4,3,
6,6,8,8,7,7,9,8,8,6,
6,5,5,5,7,6,6};
int sum = 0;
for (int i = 1; i < 1000; i++)
{
if (i <= 20)
{
sum+=array[i];
}
else if (i < 100)
{
sum += array[i % 10];
sum += array[i / 10 + 20 - 2];
}
else
{
if (i % 100 <= 20)
{
sum += array[i % 100];
}
else
{
sum += array[i % 10];
sum += array[i / 10 % 10 + 20 - 2];
}
sum += 10;//hundred and
if (i % 100 == 0)
{
sum -= 3;
}
sum += array[i / 100];
}
}
sum += 11;//one thousand
System.out.println(sum);
}
}
answer: 21124
time: 1