[Project Euler] 来做欧拉项目练习题吧: 题目017
?? ? ? ? ? ? ? ?[Project Euler] 來做歐拉項目練習題吧: 題目017
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ?周銀輝
?
題目描述:
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE:?Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
?
問題分析:
這個題目比較簡單哈,用鉛筆和紙也比如容易算出啦。比如計算單個數字的出現次數,"hundred"單詞出現的次數等等。
而用程序計算嘛,關鍵在于創(chuàng)建一個數字和對應單詞長度的映射,也就是上面numbers那個數組。
然后分離出百位數、十位數、個位數,以及處理各種特殊情況就可以了。?
#include <stdio.h>int numbers[91];
void ini_numbers(){ //為了節(jié)省空間,用hash_map也可以
numbers[0] = 0;//no pronunciation for zero? numbers[1] = 3;//"one" numbers[2] = 3;//"two" numbers[3] = 5;//"three" numbers[4] = 4;//"four" numbers[5] = 4;//"five" numbers[6] = 3;//"six" numbers[7] = 5;//"seven" numbers[8] = 5;//"eight" numbers[9] = 4;//"nine" numbers[10] = 3;//"ten" numbers[11] = 6;//"eleven" numbers[12] = 6;//"twelve" numbers[13] = 8;//"thirteen" numbers[14] = 8;//"fourteen" numbers[15] = 7;//"fifteen" numbers[16] = 7;//"sixteen" numbers[17] = 9;//"seventeen" numbers[18] = 8;//"eighteen" numbers[19] = 8;//"nineteen" numbers[20] = 6;//"twenty" numbers[30] = 6;//"thirty" numbers[40] = 5;//"forty" numbers[50] = 5;//"fifty" numbers[60] = 5;//"sixty" numbers[70] = 7;//"seventy" numbers[80] = 6;//"eighty" numbers[90] = 6;//"ninety"}
int get_length(int n){ int a=0; //hundreds'digit int b=0; //ten's digit int c=0; //units' digit int length = 0;
a = n/100; n = n%100; b = n/10; c = n%10; if(a!=0) { length += numbers[a] + 7; // 7 for "hundred" if(b!=0 || c!=0) { length += 3; //3 for "and" } }
if(b!=0) { if(b==1) { length += numbers[b*10+c]; return length; } else { length += numbers[b*10]; } }
if(c!=0) { length += numbers[c]; }
return length; }
int main(){ int i, length=0;
ini_numbers();
for(i=1; i<=999; i++) { length += get_length(i); }
length += 11; //11 for "one thousand"
printf("total length: %d\n", length); return 0;
}?
轉載于:https://www.cnblogs.com/zhouyinhui/archive/2011/03/03/1970233.html
總結
以上是生活随笔為你收集整理的[Project Euler] 来做欧拉项目练习题吧: 题目017的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: vbs向指定的日志文件添加日志
- 下一篇: 剑豪御剑九位置选择,是项链还是魔法石
