• (算法)整数转英文描述


    题目:

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

    思路:

    每三位转换一次,在适当位置插入million,thousand。即:

    convert(19 323 984)=convert(19)+" million, "+convert(323)+" thousand "+convert(984)

    代码:

    #include<iostream>
    using namespace std;
    
    string digits[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
    string teens[]={"Eleven","Twelve","ThirTteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    string tens[]={"Ten","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    string bigs[]={"","Thousand,","Million,"};
    
    string numToEnglish100(int num);
    
    string numToEnglish(int num){
        if(num==0)
            return "Zero";
        else if(num<0){
            return "Negative " + numToEnglish(-1*num);
        }
    
        int count=0;
        string str="";
    
        while(num>0){
            if(num%1000!=0){
                str=numToEnglish100(num%1000)+bigs[count]+" "+str;
            }
            num/=1000;
            count++;
        }
    
        return str;
    }
    
    string numToEnglish100(int num){
        string str="";
        if(num>=100){
            str+=digits[num/100-1]+" Hundred ";
            num%=100;
        }
    
        if(num>=11 && num<=19){
            return str+teens[num-11]+" ";
        }
        else if(num==10 || num>=20){
            str+=tens[num/10-1]+" ";
            num%=10;
        }
    
        if(num>=1 && num<=9)
            str+=digits[num-1]+" ";
    
        return str;
    }
    
    int main(){
        int num;
        while(cin>>num){
            cout<< numToEnglish(num) <<endl;
        }
        return 0;
    }
  • 相关阅读:
    nodejs实现端到端加密
    DiffieHellman(迪菲-赫尔曼)密钥交换算法原理及其实现
    MongoDB主备 版本3.6.5
    linux源地址转换
    Mac下IDEA快捷键操作
    Ubuntu离线安装gcc
    VM安装Mac时,使用Unlocker12 插件时报getTools错误的问题
    华为OSPF与ACL综合应用实例讲解
    基于全局地址池的DHCP
    浮动静态路由及负载均衡
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4899198.html
Copyright © 2020-2023  润新知