LeetCode 273. Integer to English Words

题目

很简单的模拟题啦

class Solution {
public:
    
     string number1[20] = { "Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
string number3[10] = { "Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety" };
string number4[10] = { "Hundred","","Thousand","Million","Billion" };

string numberToWords2(int num)
{
    string ans = "";
    int a = num / 100;
    num %= 100;
    int b = num / 10;
    num %= 10;
    int c = num;
    if (a != 0)
    {
        ans += number1[a];
        ans += " ";
        ans += number4[0];
        ans += " ";
    }

    if (b >= 2)
    {
        ans += number3[b - 2];
        ans += " ";
    }
    else if (b == 1)
    {
        ans += number1[10 + c];
        ans += " ";
        ans = ans.substr(0, ans.size() - 1);
        return ans;
    }
    
    if (c != 0)
    {
        ans += number1[c];
        ans += " ";
    }

    ans = ans.substr(0, ans.size() - 1);
    return ans;
}
    
string function(int num1,int num2,int pos)
{
    string ans="";
    int x = num1 / num2;
    if (x != 0)
    {
        string y = numberToWords2(x);
        ans += y;
        ans += " ";
        if(number4[pos]!="")
        {
            ans += number4[pos];
            ans += " ";
        }
    }
    
    return ans;

}

string numberToWords(int num) {

    string ans = "";
    
    int x = 1000000000;
    for(int i=4;i>=1;i--)
    {
        ans += function(num,x,i);
        num %= x;
        x/=1000;
    }
   
    if (ans == "")
        ans = "Zero";

    if(ans[ans.size()-1]==' ')
    ans = ans.substr(0, ans.size() - 1);
    return ans;
}

};
原文地址:https://www.cnblogs.com/dacc123/p/12858136.html