题解 | #人民币转换#

人民币转换

http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b


function transferMoney(str) {
  const res = []
  let zero_pre = false // 确保在连续‘0’的情况下,只有一个'零'
  // 倒着转化
  for (let i = str.length - 1; i >= 0; i--) {
    const c = str[i]
    if (c === '0') {
      if (!zero_pre) {
        zero_pre = true
        res.push(num[Number(c)])
      } 
    }else {
        zero_pre = false
        res.push(pro[str.length - 1 - i], num[Number(c)])
      }
  }
  res.reverse()
  // console.log(res)
  // 去掉后面所有的 ”零“
  while (res[res.length - 1] === '零') {
    res.pop()
  }
  return res.join('').replace('壹拾', '拾')
}

const num = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const pro = ['', '拾', '佰', '仟', '万', '亿', '元', '角', '分', '整']

const [n, m] = readline().split('.')
const res = ['人民币']
if (n.length > 8) {
  const c = transferMoney(n.slice(0, -8))
  res.push(c + '亿')
}
if (n.length > 4) {
  const c = transferMoney(n.slice(-8, -4))
  res.push(c + '万')
}
if (n !== '0') {
  const c = transferMoney(n.slice(-4))
  res.push(c + '元')
}
if (m === '00') {
  res.push('整')
} else {
  if (m[0] > 0) {
    const c = num[Number(m[0])]
    res.push(c + '角')
  }
  if (m[1] > 0) {
    const c = num[Number(m[1])]
    res.push(c + '分')
  }
}
console.log(res.join(''))
全部评论

相关推荐

11-29 00:55
门头沟学院
区域赛银,邀请赛金,打算十二月打下Java基础、背点八股、写个外卖后去投福建小厂的寒假实习,简历应该怎么写呢?以及福州/和厦门有推荐的小厂吗?
牛客53210502...:简历一页:把区域银,邀请赛金标粗,其他的奖除非凑一页否则没有必要写。或者多页:每个站一行这样都列出来。项目经历看看牛客其他人是怎么写的,写的不好呢。简历打磨好按部就班没问题的
点赞 评论 收藏
分享
算法冲刺中:kpi面加一,面完完全没动静,感谢信都没有
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务