题解 | #人民币转换#

人民币转换

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(''))
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务