《Cracking the Coding Interview程式設計師面試金典》----數字發音

塵封的記憶0發表於2017-05-03
時間限制:3秒 空間限制:32768K 熱度指數:325
本題知識點: 程式設計基礎
 演算法知識視訊講解

題目描述

有一個非負整數,請編寫一個演算法,列印該整數的英文描述。

給定一個int x,請返回一個string,為該整數的英文描述。

測試樣例:
1234

返回:"One Thousand,Two Hundred Thirty Four"

思路:這道題不難,但是很麻煩,要一點一點想清楚才能寫

程式碼如下:

class ToString {
public:
    string toString(int x) {
string base[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
                           "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                            "Eighteen", "Nineteen"};  //0~19
        string tyNum[10] = {"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"};
        string bigNum[4] = {"", "Thousand", "Million", "Billion"};
        string res;
        int k=0;
        //將x每3位數分成一組進行編碼
        while(x>0){
            int val = x%1000;
            //對每3位數進行編碼
            string temp;
            if(base[val/100]!=""){
                temp+=base[val/100];
                temp+=" Hundred";
            }
            if(val%100<20){  //小於20的數單獨編碼
                if(!temp.empty())temp+=" ";
                temp+=base[val%100];
            }else{
                if(!temp.empty())temp+=" ";
                temp+=tyNum[val%100/10];
                if(base[val%10]!=""){
                    if(!temp.empty())temp+=" ";
                    temp+=base[val%10];
                }
            }
            if(!temp.empty()&&bigNum[k]!=""){
                temp+=" ";
                temp+=bigNum[k];
                if(!res.empty())temp+=",";
            }
            res = temp+res;
            k++;
            x /= 1000;
        }
        return res;
    }
};

不懂的可以加我的QQ群:261035036(IT程式設計師面試寶典

群) 歡迎你到來哦,看了博文給點腳印唄,謝謝啦~~


相關文章