273. 整数转换英文表示

题目链接:273. 整数转换英文表示 - 力扣(LeetCode)

 

 

 

 

 

 

 

 

 

 

 

解析:

中文转英文:每三位一组,先用英文表示,然后从第二组开始向后几组分别增加单位

"Thousand", "Million", "Billion"
比如101001
"One Hundred One Thousand One"
 
class Solution {
public:

    vector<string> singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    vector<string> teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    vector<string> tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    vector<string> thousands = {"", "Thousand", "Million", "Billion"};

    string get_english(int temp) {
        string ret = "";
        int a = temp / 100;
        if (a > 0) {
            ret = singles[a] + " Hundred";
        }
        temp -= a * 100;
        if (temp == 0) return ret;
        else if (temp < 20) {
            if (ret != "") ret += " ";
            if (temp < 10) ret += singles[temp];
            else ret += teens[temp - 10];
        } else {
            if (ret != "") ret += " ";
            int b = temp / 10;
            ret += tens[b];
            temp -= b * 10;
            if (temp == 0) return ret;
            ret += " ";
            ret += singles[temp];
            return ret;
        }
        return ret;
    }

    string numberToWords(int num) {
        if (num == 0) return "Zero";
        string ret = "";
        int cnt = 0;
        while(num) {
            int temp = num % 1000;
            string temp_str = get_english(temp);            
            if (temp_str != "" && thousands[cnt] != "") temp_str += " " + thousands[cnt];
            if (ret != "" && temp_str != "") temp_str += " "; 
            ret = temp_str + ret;
            cnt++;
            num /= 1000;
        }
        return ret;

        
    }
};

 

posted @ 2025-12-22 22:06  WTSRUVF  阅读(1)  评论(0)    收藏  举报