题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
//这题采用递归的方法,以每四位数为一个阶梯进行递归,直到单位为亿为止 // Write your code here while(line = readline()){ let obj1={1:'壹',2: '贰',3:'叁',4:'肆',5:'伍',6:'陆',7:'柒',8:'捌',9:'玖'} let arr1=['拾', '佰' ,'仟' ,'万' ,'亿'] let arr2=['元', '角' ,'分' ,'零' ,'整'] let res='' let money =line.split('.') if(Number(money[0])==0) {//如果整数部分为零 if(Number(money[1])>9) res='人民币'+obj1[money[1][0]]+arr2[1]+(Number(money[1][1])>0?obj1[money[1][1]]+arr2[2]:'') else res='人民币'+obj1[money[1][0]]+arr2[2] } else if(Number(money[1])==0) res='人民币'+func(Number(money[0]))+arr2[0]+arr2[4]//整数部分不为0,小数部分为0 else {//均不为0 if(Number(money[1])>9) res='人民币'+func(Number(money[0]))+arr2[0]+obj1[money[1][0]]+arr2[1]+(Number(money[1][1])>0?obj1[money[1][1]]+arr2[2]:'') else res='人民币'+func(Number(money[0]))+arr2[0]+obj1[money[1][1]]+arr2[2] } console.log(res) function func(e){ if(e<10) return obj1[e] else if(e<100) { return (Math.floor(e/10)>1?obj1[Math.floor(e/10)]:'')+arr1[0]+(e%10>0?obj1[e%10]:'') } else if(e<1000){ return obj1[Math.floor(e/100)]+arr1[1]+(e%100>0?e%100>10?func(e%100):(arr2[3]+func(e%100)):'') } else if(e<10000){ return obj1[Math.floor(e/1000)]+arr1[2]+(e%1000>0?e%1000>100?func(e%1000):(arr2[3]+func(e%1000)):'') } else if(e<1e8){//这是小于一亿的情况,从这里开始采用递归 return func(Math.floor(e/10000))+arr1[3]+(e%10000>0?e%10000>1000?func(e%10000):(arr2[3]+func(e%10000)):'') } else if(e>=1e8){//这是大于一亿的情况,这里同样采用递归 return func(Math.floor(e/1e8))+arr1[4]+(e%1e8>0?func(e%1e8):'') } } }