描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
具体规则如下:
1.在英语读法中三位数字看成一整体,后面再加一个计数单位。从最右边往左数,三位一单位,例如12,345 等
2.每三位数后记得带上计数单位 分别是thousand, million, billion.
3.公式:百万以下千以上的数 X thousand X, 10亿以下百万以上的数:X million X thousand X, 10 亿以上的数:X billion X million X thousand X. 每个X分别代表三位数或两位数或一位数。
4.在英式英语中百位数和十位数之间要加and,美式英语中则会省略,我们这个题目采用加上and,百分位为零的话,这道题目我们省略and
下面再看几个数字例句:
22: twenty two
100: one hundred
145: one hundred and forty five
1,234: one thousand two hundred and thirty four
8,088: eight thousand (and) eighty eight (注:这个and可加可不加,这个题目我们选择不加)
486,669: four hundred and eighty six thousand six hundred and sixty nine
1,652,510: one million six hundred and fifty two thousand five hundred and ten
说明:
数字为正整数,不考虑小数,转化结果为英文小写;
保证输入的数据合法
关键字提示:and,billion,million,thousand,hundred。
数据范围:1 \le n \le 2000000 \1≤n≤2000000
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
示例1
输入:
22
复制输出:
twenty two
复制
我的解答:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
long long n;
cin >> n;
// 低位,0-9,
string lowDigit[20] = {"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen" };
// 十位, 四十用forty,而不是fourty
string tenDigit[10] = {"0", "1", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety"};
// 关键字提示:and,billion,million,thousand,hundred。
string keyWord[5] = {"0", "hundred", "thousand", "million", "billian"};
// 结果
string result = "";
// 当前处理的轮数
int round = 1;
while(n != 0){
// 当前处理的最后三位数
int curThree = n % 1000;
// 当前三个数字的零时结果
string curStr = "";
// 当前三位数字的后边两位数字是多少
int curTwo = curThree % 100;
// 倒数第一位
int lastOne = curThree % 10;
// 倒数第二位
int lastTwo = curThree / 10 % 10;
// 倒数第三位
int lastThree = curThree / 100;
if(curTwo >= 1 && curTwo <= 19){
curStr = lowDigit[curTwo];
}else if(curTwo >= 20 && curTwo <= 99){
// 这个时候十位是不会为0的,个位有可能是0
if(lastOne != 0) {
curStr = lowDigit[ lastOne ];
//个位,十位都不是0
curStr = tenDigit[lastTwo] + ' ' + curStr;
// 个位有可能是0, 十位肯定不是0
} else{
curStr = tenDigit[lastTwo];
}
}else if(curTwo == 0){
// else if( curTwo == 0 ) { } 如果这三位数字的后两位是0,跳过了, curStr就是空字符串
}
// 如果十位是0,这个"and"要不要加? 似乎是要加, 测试了一下确实要加,但是题目里没说清楚
if(lastThree != 0){
// 如果最后两位不是0
if(curTwo != 0){
curStr = lowDigit[lastThree] + " hundred and " + curStr;
}
else{
// 可能会带来一个字符串最后一个是空格的问题
// 当最后两个数字是0的时候,curStr就是空字符串,不必拼接到最后边了
// curStr = lowDigit[lastThree] + " hundred " + curStr;
curStr = lowDigit[lastThree] + " hundred";
if(round > 1) curStr += ' ';
}
}
if(round >= 2){
curStr = curStr + ' ' + keyWord[round] + ' ';
}
result = curStr + result;
n /= 1000;
round ++;
}
cout << result;
return 0;
}
1159

被折叠的 条评论
为什么被折叠?



