zoukankan      html  css  js  c++  java
  • LeetCode "Integer to English Words"

    Just take care of corner cases.

    vector<string> sec3 = { "", "Thousand", "Million", "Billion" };
    vector<string> sig = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    vector<string> teen = { "", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
    "Seventeen", "Eighteen", "Nineteen" };
    vector<string> ty = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    
    class Solution
    {
        string sec3to(int num)
        {
            int a = num % 10;
            int b = (num / 10) % 10;
            int c = (num / 100) % 10;
    
            string ret;
            if (b == 1 && a != 0) // teens
            {
                ret += teen[a];
            }
            else if (a == 0 && b != 0) // ty-s
            {
                ret += ty[b];
            }
            else // all other
            {
                if (b > 0) ret += ty[b] + " ";
                if (a > 0) ret += sig[a];
            }
            if (c > 0)
            {
                string hstr = sig[c] + " Hundred";
                if (ret.empty())
                    ret = hstr;
                else
                    ret = hstr + " " + ret;
            }
    
            return ret;
        }
    public:
        string numberToWords(int num)
        {
            if (num == 0) return "Zero";
            string ret;
    
            int sec = num % 1000;
            int seci = 0;
            while (num)
            {
                string secstr = sec3to(sec);
                if (!secstr.empty())
                    ret = secstr + (seci > 0 ? (" " + sec3[seci] + (ret.empty() ? "" : " " + ret)) : "");
    
                //
                num /= 1000;
                sec = num % 1000;
                seci++;
            }
    
            return ret;
        }
    };
    View Code
  • 相关阅读:
    例子2.5
    例子2.4
    例子2.3
    例2
    例2.1
    快闪PPT 快速入门教程 脑洞大开,特效随你定 ----口袋动画PA(初学易上手001):
    Linux 基础与应用教程 0011(DNS解析)
    课外阅读记录:001
    好的特效模板
    学习记住并且时常要打开去看的VIM
  • 原文地址:https://www.cnblogs.com/tonix/p/4775485.html
Copyright © 2011-2022 走看看