给定一个数值,输出符合中国人习惯的读法--记一道笔试题

题目:给定一个数字,最大小于一万亿,输出符合中国人习惯的读法,例如:

  a、12输出:十二

  b、102输出:一百零二

  c、1002输出:一千零二

  d、112输出:一百十二

  e、10112输出:一万零一百十二

  f、120000000:一亿二千万

  g、11021002:一千一百零二万一千零二

  h、11020102:一千一百零二万零一百零二

  i、1000001:一百万零一

  j、1000000001:十亿零一

  嗯,一道笔试题,解的很没有节操,没有太好的思路,只能尽力抽取翻译过程中的共有代码,尽量写的不那么难看。

  基本思路就是把输入的数补全为12位,然后三等分,分别转换计算,然后拼接起来。

  PS:感觉中文语言坑比较多,越写越丑。

  1 #include <iostream>
  2 #include <vector>
  3 #include <string>
  4 
  5 //判断该位置后是否还有非零数 
  6 bool NoPosAfter(std::string str, int index)
  7 {
  8     int len = str.size();
  9     for(int i = index+1; i < len; ++i)
 10     {
 11         if(str[i] != '0')return false;
 12     }
 13     return true;
 14 }
 15  
 16 std::string convert(std::string str)
 17 {
 18     std::vector<std::string> unit{"", "", "", ""};
 19     std::vector<std::string> num{"", "", "", "", "", "", "", "", "", ""};
 20 
 21     std::string ret("");
 22 
 23     int i = 0;
 24     while(i < 4 && str[i] == '0') ++i;
 25     if(i == 4) return ret;
 26     while(i < 4)
 27     {
 28         if(str[i] == '0')
 29         {
 30             if(NoPosAfter(str, i))
 31             {
 32                 return ret;
 33             }
 34             else
 35             {
 36                 if(i > 0)
 37                     if(str[i-1] != '0')
 38                         ret += "";
 39             }
 40         }
 41         else
 42         {
 43             ret += num[str[i]-'0'] + unit[3-i];
 44         }
 45         ++i;
 46     }
 47 
 48     return ret;
 49 }
 50 
 51 void print(std::string input)
 52 {
 53     std::string cstr(12, '0');
 54     cstr.replace(12-input.size(), input.size(), input);
 55 
 56     std::string Ystr(cstr, 0, 4);
 57     std::string Wstr(cstr, 4, 4);
 58     std::string Lstr(cstr, 8, 4);
 59 
 60     std::string result;
 61 
 62     auto Yret = convert(Ystr);
 63     auto Wret = convert(Wstr);
 64     auto Lret = convert(Lstr);
 65 
 66     bool high = false;//高位标志 
 67     if(Yret.size() != 0)
 68     {
 69         result += Yret + "亿";
 70         high = true;
 71     }
 72     
 73     if(Wret.size() != 0)
 74     {
 75         if(Wstr < "1000" && high) result += "";
 76         result += Wret + "";
 77         high = true;
 78     }
 79     else if(Lret.size() != 0)
 80     {
 81         if(high)result += "";
 82     }
 83     
 84     if(Lret.size() != 0)
 85     {
 86         if(Lstr < "1000" && high && Wret.size()) result += "";
 87         result += Lret;
 88     }
 89 
 90     if(result.find("一十") == 0)
 91     {
 92         result.erase(0, 2);
 93     }
 94     
 95     std::cout << result << std::endl;
 96 }
 97 
 98 int main()
 99 {
100     print("112");
101     print("10112");
102     print("120000000");
103     print("11021002");
104     print("11020102");
105     print("1000001");
106 
107     return 0;
108 }
View Code

 

posted @ 2015-06-17 19:46  eagleliwx  阅读(379)  评论(0编辑  收藏  举报