首页 > 代码库 > careercup-中等难度 17.7
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);}
careercup-中等难度 17.7
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。