(算法)整数转汉字描述
题目:
给定一个整数,打印该整数的汉字描述。(例如:11001:“一万一千零一”)
思路:
按照以下位数来转换:
亿级
万级
千及千以下
代码:
由于编程环境不支持中文,故以拼音代替,若需转为汉字,只需改为对应汉字并将代码中的空格符去掉即可。
#include<iostream> using namespace std; string bigs[3]={"","Wan","Yi"}; string level[4]={"Qian","Bai","Shi",""}; string digits[10]={"Ling","Yi","Er","San","Si","Wu","Liu","Qi","Ba","Jiu"}; string numToChinese1000(int num,int offset); string numToChinese(int num){ if(num>=0 && num<10){ return digits[num]; } else if(num<0) return "Fu "+numToChinese(-1*num); string str=""; int count=0; while(num>0){ if(num%10000!=0){ str=numToChinese1000(num%10000,count)+bigs[count]+" "+str; } num=num/10000; count++; } return str; } string numToChinese1000(int num,int offset){ string str=""; int n=1000; int count=0; bool IsZero=true; bool IsOn=false; if(offset>0 && num>0 && num<=9) return digits[num]+" "; while(num>0){ IsZero=true; if(num>=n){ str+=digits[num/n]+" "+level[count]+" "; num=num%n; IsZero=false; } if((!IsOn) && IsZero){ str+=digits[0]+" "; IsOn=true; } n=n/10; count++; } return str; } int main(){ int num; while(cin>>num){ cout<< numToChinese(num) <<endl; } return 0; }