javascript 题解

阿拉伯数字转中文

http://www.nowcoder.com/practice/6eec992558164276a51d86d71678b300

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return string字符串
 */
function num2cn(n) {
  const isLose = n < 0 // 是不是负数
  n = Math.abs(n).toString()
  const res = [], len = n.length
  
  // 四位做一次转译
  for (let i = len; i > 0; i -= 4) {
    res.push(NumToChina(n.slice(Math.max(0, i - 4) ,i)))
  }

  const unit = ['', '万', '亿']
  for (let i = 0; i < res.length; i++) {
    // 如果四位数都为 0,则会为空,这种不需要填单位了
    if (res[i] === '') continue
    res[i] += unit[i]
  }
  
  isLose && res.push('负')

  return res.reverse().join('')
}

function NumToChina(n) {
  n = n.toString()
  if (n === '0') return '零'
  const unit = ['', '十','百', '千']
  const number = ['零','一','二','三','四','五','六','七','八','九']
  const len = n.length
  let res = ''
  for (let i = 0; i < len; i++) {
    const num = Number(n[i])
    // 多个零只加入一个零,如 1006
    if (num !== 0) {
      if (n[i - 1] === '0') res += '零'
      // 先数字后单位
      res += number[num] + unit[len - i - 1]
    }
  }
  // 12 会为 一十二,但正确应该为 十二,所以当十位数是一且只有两位数字的时候,去掉前面的一
  if (len === 2 && n[0] === '1') res = res.slice(1)
  return res
}

module.exports = {
    num2cn : num2cn
};
全部评论

相关推荐

评论
3
1
分享

创作者周榜

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