top1编程
← 返回题目
题解

【提高】英文翻译

1 条题解

  • 0
    @ 2026-7-30 1:08:41

    解题思路

    逐个处理英文单词或字符,并按照题目给出的翻译规则输出。

    参考代码

    // 这道题的做法:先读入题目给出的数据,再用简单的循环和判断完成要求。
    #include <iostream>
    #include <string>
    using namespace std;
    // 1-19的英文单词
    string less20[] = {
    "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                       "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
    ;
    // 整十的英文单词
    string tens[] = {
    "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}
    ;
    // 量级单位,从低到高:千、百万、十亿
    string scales[] = {
    "thousand", "million", "billion"}
    ;
    // 将三位数转换为英文
    string convertThreeDigits(int num) {
        string result;
        int hundred = num / 100;
        int rest = num % 100;
        // 处理百位
        if (hundred > 0) {
            result += less20[hundred] + " hundred";
            if (rest > 0) result += " and ";
        }
        // 处理十位和个位
        if (rest > 0) {
            if (rest < 20) {
                result += less20[rest];
            }
     else {
                result += tens[rest / 10];
                int single = rest % 10;
                if (single > 0) result += " " + less20[single];
            }
        }
        return result;
    }
    // 将数字转换为英文
    string numberToEnglish(int n) {
        if (n == 0) return "zero";
        string result;
        // 按三位一组拆分数字,从右到左处理
        int i = 0;
        while (n > 0) {
            int mod = n % 1000;
            n = n / 1000;
            string part = convertThreeDigits(mod);
            if (!part.empty()) {
                if (!result.empty()) part += " " + scales[i];
                if (!result.empty()) result = part + " " + result;
                else result = part;
            }
            i++;
        }
        return result;
    }
    int main() {
        int n;
        cin >> n;
        cout << numberToEnglish(n) << endl;
        return 0;
    }
    
    

    复杂度

    代码只使用了简单变量、循环和判断。若循环检查了 n 个数据,时间复杂度通常为 O(n);没有开辟与输入规模相关的额外数组时,空间复杂度为 O(1)。

    • 1