美文网首页
Leetcode-273-Integer to English

Leetcode-273-Integer to English

作者: 单调不减 | 来源:发表于2019-06-02 11:08 被阅读0次

    这是一道细节题,没有什么思维量,但是写的时候要小心空格问题和零的处理。

    代码如下:

    class Solution {
    public:
        string threeDigit(int num, map<int,string>& mp)
        {
            string str="";
            if(num==0) return str;
            if(num>=100)
            {
                str+=mp[num/100]+" "+"Hundred"+" ";
                num-=num/100*100;
            }
            if(num==0) return str;
            if(num<=20) return str+mp[num]+" ";
            str+=mp[num/10*10]+" ";
            num-=num/10*10;
            if(num!=0) str+=mp[num]+" ";
            return str;
        }
        string numberToWords(int num) {
            if(num==0) return "Zero";
            map<int,string> Digit={{0,""},{1,"Thousand"},{2,"Million"},{3,"Billion"}};
            map<int,string> mp={{1,"One"},{2,"Two"},{3,"Three"},{4,"Four"},{5,"Five"},
            {6,"Six"},{7,"Seven"},{8,"Eight"},{9,"Nine"},{10,"Ten"},{11,"Eleven"},
            {12,"Twelve"},{13,"Thirteen"},{14,"Fourteen"},{15,"Fifteen"},{16,"Sixteen"},
            {17,"Seventeen"},{18,"Eighteen"},{19,"Nineteen"},{20,"Twenty"},{30,"Thirty"},
            {40,"Forty"},{50,"Fifty"},{60,"Sixty"},{70,"Seventy"},{80,"Eighty"},{90,"Ninety"}};
            vector<int> nums;
            int cnt=0,now=0;
            while(num)
            {
                now+=(num%10)*pow(10,cnt);
                num/=10;
                cnt++;
                if(cnt==3)
                {
                    nums.push_back(now);
                    cnt=0;
                    now=0;
                }
            }
            if(now) nums.push_back(now);
            string res;
            int n=nums.size();
            for(int i=n-1;i>=0;i--)
            {   
                string str=threeDigit(nums[i],mp);
                if(str!="")
                    res+=str+Digit[i]+" ";
            }
            int k=res.size()-1;
            while(k>=0&&res[k]==' ') k--;
            return res.substr(0,k+1);
        }
    };
    

    相关文章

      网友评论

          本文标题:Leetcode-273-Integer to English

          本文链接:https://www.haomeiwen.com/subject/mexxxctx.html