难度:8+
输入格式
一个自然数n,0< =n< =2^31-1。
输出格式
输出这个数的英文,最后不要有多余的空格。
输入数据 1
1111111111
输出数据 1
one billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven
代码:
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
// 定义数字到英文的映射
const string units[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
const string teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
const string tens[] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
const string thousands[] = {"", "thousand", "million", "billion"};
// 将三位数转换为英文
string numberToWords(int num) {
if (num == 0) return "zero";
if (num < 10) return units[num];
if (num < 20) return teens[num - 10];
if (num < 100) return tens[num / 10] + (num % 10 != 0 ? " " + units[num % 10] : "");
if (num < 1000) return units[num / 100] + " hundred" + (num % 100 != 0 ? " and " + numberToWords(num % 100) : "");
return "";
}
// 将大数字转换为英文
string convertToEnglish(long long num) {
if (num == 0) return "zero";
vector<string> parts;
int unit = 0;
while (num > 0) {
if (num % 1000 != 0) {
parts.push_back(numberToWords(num % 1000) + " " + thousands[unit]);
}
unit++;
num /= 1000;
}
reverse(parts.begin(), parts.end());
return parts[0] + (parts.size() > 1 ? " " + parts[1] : "");
}
int main() {
long long n;
cin >> n;
cout << convertToEnglish(n) << endl;
return 0;
}
标签:英文翻译,10,return,string,提高,parts,num,const,P1126
From: https://blog.csdn.net/MAX20131115/article/details/145211325