程序員面試金典 16.8

English Int:將整數轉換爲英文表示。

用英文表示數字時,每3位作爲一部分,然後分別補上BillionMillionThousand,所以問題可以轉化爲對包含3個數字的整數進行轉換。

3位數字則先轉換百位,然後判斷剩餘的兩位數是否有特殊的英文表示,沒有則依次轉換十位和個位,其中要特別注意對0的處理,反正多提交幾次就知道哪裏錯了。

class Solution {
public:
    string numberToWords(int num) {
        if(num == 0) return vsSpec[0];
        if(num < 0){
            ret.append(strNeg);
            num = -num;
        }
        convertPerThousand(num, 0);
        ret.pop_back();
        return ret;
    }
    void convertPerThousand(int num, const int big)
    {
        if(num >= 1000){
            convertPerThousand(num / 1000, big + 1);
            num %= 1000;
        }
        if(num != 0){
            convertDigit(num);
            ret.append(vsThousands[big]);
        }
    }
    void convertDigit(int num)
    {
        if(num >= 100){
            convertHundred(num / 100);
            num %= 100;
        }
        if(num >= 20){
            convertTen(num / 10);
            num %= 10;
        }
        if(num != 0){
            ret.append(vsSpec[num]); 
        }
    }
    void convertHundred(int num)
    {
        ret.append(vsSpec[num]);
        ret.append(strHrd);
    }
    void convertTen(int num)
    {
        ret.append(vsTens[num]);
    }
private:
    string ret;
    const vector<string> vsSpec = { 
        "Zero", "One ", "Two ", "Three ", "Four ",
        "Five ", "Six ", "Seven ", "Eight ", "Nine ",
        "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ",
        "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "
    };
    const vector<string> vsTens = {
        "", "", "Twenty ", "Thirty ", "Forty ",
        "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "
    };
    const vector<string> vsThousands = {
        "", "Thousand ", "Million ", "Billion "
    };
    const string strHrd = "Hundred ";
    const string strNeg = "Negative ";
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章