zoukankan      html  css  js  c++  java
  • 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;
    }
    
    };
    
  • 相关阅读:
    建立文件结构
    PCL类的设计结构
    如何编写新的PCL类
    PCL推荐的命名规范(2)
    PCL推荐的命名规范(1)
    PCL中异常处理机制
    如何增加新的PointT类型
    hdoj 1728 逃离迷宫
    ny710 外星人的供给站
    ny714 Card Trick
  • 原文地址:https://www.cnblogs.com/dacc123/p/12858136.html
Copyright © 2011-2022 走看看