《Cracking the Coding Interview》——第17章:普通题——题目7

时间:2014-04-29 15:29:44   收藏:0   阅读:423

2014-04-28 23:28

题目:给定一个数字,用英语把它读出来。

解法:ZOJ上有相反的题目。如果我要用中文读书来呢?

代码:

bubuko.com,布布扣
  1 // 17.7 Read an integer in English.
  2 #include <map>
  3 #include <string>
  4 using namespace std;
  5 
  6 map<int, string> m;
  7 
  8 void init()
  9 {
 10     m[0] = "zero";
 11     m[1] = "one";
 12     m[2] = "two";
 13     m[3] = "three";
 14     m[4] = "four";
 15     m[5] = "five";
 16     m[6] = "six";
 17     m[7] = "seven";
 18     m[8] = "eight";
 19     m[9] = "nine";
 20     m[10] = "ten";
 21     m[11] = "eleven";
 22     m[12] = "twelve";
 23     m[13] = "thirteen";
 24     m[14] = "fourteen";
 25     m[15] = "fifteen";
 26     m[16] = "sixteen";
 27     m[17] = "seventeen";
 28     m[18] = "eighteen";
 29     m[19] = "nineteen";
 30     m[20] = "twenty";
 31     m[30] = "thirty";
 32     m[40] = "forty";
 33     m[50] = "fifty";
 34     m[60] = "sixty";
 35     m[70] = "seventy";
 36     m[80] = "eighty";
 37     m[90] = "ninety";
 38     int i, j;
 39     for (i = 2; i <= 9; ++i) {
 40         for (j = 1; j <= 9; ++j) {
 41             m[i * 10 + j] = m[i * 10] + "-" + m[j];
 42         }
 43     }
 44 }
 45 
 46 void readNumber(int n)
 47 {
 48     if (n == 0) {
 49         return;
 50     }
 51     // here n is limited between [0, 999];
 52     int a, b, c;
 53     
 54     a = n / 100;
 55     b = n % 100 / 10;
 56     c = n % 10 / 1;
 57     
 58     if (a > 0) {
 59         printf("%s hundred ", m[a].c_str());
 60         if (b != 0 || c != 0) {
 61             printf("and ");
 62         }
 63     }
 64     if (b * 10 + c > 0) {
 65         printf("%s ", m[b * 10 + c].c_str());
 66     }
 67 }
 68 
 69 int main()
 70 {
 71     init();
 72     int n, n0;
 73     
 74     while (scanf("%d", &n) == 1) {
 75         if (n == 0) {
 76             printf("zero \n");
 77             continue;
 78         }
 79         if (n < 0) {
 80             printf("minus ");
 81             n = -n;
 82         }
 83         n0 = n;
 84         if (n >= 1000000000) {
 85             readNumber(n / 1000000000);
 86             printf("billion ");
 87             n = n % 1000000000;
 88         }
 89         if (n >= 1000000) {
 90             readNumber(n / 1000000);
 91             n = n % 1000000;
 92             printf("million ");
 93         }
 94         if (n >= 1000) {
 95             readNumber(n / 1000);
 96             n = n % 1000;
 97             printf("thousand ");
 98         }
 99         if (n0 >= 1000 && n / 100 == 0) {
100             printf("and ");
101         }
102         readNumber(n);
103         putchar(\n);
104     }
105     
106     return 0;
107 }
bubuko.com,布布扣

 

《Cracking the Coding Interview》——第17章:普通题——题目7,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!