• careercup-中等难度 17.7


    17.7 给定一个整数,打印该整数的英文描述(例如“One Thousand,Two Hundred Thirty Four”)。

    解法:

    举个例子,在转换19 323 984时,我们可以考虑分段处理,没三位转换一次,并在适当的地方插入“thousand”(千)和“million”(百万)。也即,

    convert(19 323 984)=convert(19)+ “ million ”+convert(323)+“ thousand ”+convert(984);

    C++实现代码:

    #include<iostream>
    #include<string>
    using namespace std;
    
    string digits[10]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
    
    string teens[10]={"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    
    string tens[10]={"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    
    string big[10]={"","Thousand","Million"};
    
    string numToString100(int number)
    {
        string str;
        if(number>100)
        {
            str+=digits[number/100-1]+" Hundred ";
        }
        number%=100;
        if(number>=11&&number<=19)
        {
            return str+teens[number-11]+" ";
        }
        else if(number==10||number>=20)
        {
            str+=tens[number/10-1]+" ";
            number%=10;
        }
        if(number>=1&&number<=9)
        {
            str+=digits[number-1]+" ";
        }
        return str;
    }
    string  numToString(int number)
    {
        if(number==0)
        {
            return "Zero";
        }
        else if(number<0)
        {
            return " Negative "+numToString(-1*number);
        }
        int count=0;
        string str=" ";
        while(number>0)
        {
            if(number%1000)
            {
                str=numToString100(number%1000)+big[count]+" "+str;
            }
            number/=1000;
            count++;
        }
        return str;
    }
    
    int main()
    {
        cout<<numToString(1109);
    }
  • 相关阅读:
    程序员的困境
    linux中获取系统时间 gettimeofday函数
    Vim 模式及常用命令整理
    使用stringstream进行类型转换与字符串分割
    EasyNet开源项目计划
    用Akka构建一个简易的分布式文件系统
    SolrCloud攻略
    EasyNet.Solr 4.4.0发布及例子
    axis2调用webservice
    Oracle常用函数2查询
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4160959.html
Copyright © 2020-2023  润新知