Talk is cheap, show me the code.
一、问题描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
方法原型:public static String parse(long num)
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
输入例子:
2356
输出例子:
two thousand three hundred and fifty six
二、问题分析
这道题就是字符串处理,但是很多细节需要注意,比如空格的问题,and的位置问题,单词的拼写问题。主要思路是,三位数三位数地处理。
#include <iostream>
#include <string>
using namespace std;
string convert(int n)
{
string change[9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
string ten[10] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen"};
string a[8] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
int m = 0, s = 0, t = 0;
m = n % 10;
n = n / 10;
if (n != 0)
s = n % 10;
n = n / 10;
if (n != 0)
t = n % 10;
string str;
if (t != 0)
str = str + change[t - 1] + " hundred";
if (s != 0 || m != 0)
{
if (t != 0)
str = str + " and ";
if (s == 1)
{
str = str + ten[m];
} else if (s != 0) {
str = str + a[s - 2];
}
if (s != 1 && m != 0)
{
if (s != 0)
str = str + " " + change[m - 1];
else
str = str + change[m - 1];
}
}
return str;
}
int main()
{
long num;
while (cin >> num)
{
int n1 = 0, n2 = 0, n3 = 0, n4 = 0;
n1 = num % 1000;
num = num / 1000;
if (num != 0)
n2 = num % 1000;
num /= 1000;
if (num != 0)
n3 = num % 1000;
num /= 1000;
if (num != 0)
n4 = num % 1000;
string s;
if (n4 != 0)
s = s + convert(n4) + " billion ";
if (n3 != 0)
s = s + convert(n3) + " million ";
if (n2 != 0)
s = s + convert(n2) + " thousand ";
s = s + convert(n1);
cout << s << endl;
}
return 0;
}