码迷,mamicode.com
首页 > 其他好文 > 详细

careercup-中等难度 17.7

时间:2014-12-13 10:45:57      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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);
}

 

careercup-中等难度 17.7

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/wuchanming/p/4160959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!