题解 | #学英语#

学英语

http://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc

const ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
const tens = [
  'ten',
  'eleven',
  'twelve',
  'thirteen',
  'forteen',
  'fifteen',
  'sixteen',
  'seventeen',
  'eighteen',
  'nineteen',
]
const twieties = ['zero', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

const range = [1e2, 1e3, 1e6, 1e9, 1e12]
const ranges = ['hundred', 'thousand', 'million', 'billion']

function transfer(num) {
  // terminor
  if (num <= 9) return ones[num]
  if (num <= 19) return tens[num % 10]
  if (num <= 99) return twieties[Math.floor(num / 10)] + (num % 10 == 0 ? '' : ' ' + ones[num % 10])

  // 递归调用
  for (let i = 0; i < 4; i++) {
    if (num < range[i + 1]) {
      return (
        transfer(Math.floor(num / range[i])) +
        ' ' +
        ranges[i] +
        (num % range[i] == 0 ? ' ' : (i != 0 ? ' ' : ' and ') + transfer(num % range[i]))
      )
    }
  }
  return ''
}

// const num = Number('2222222') // two million two hundred and twenty two thousand two hundred and twenty two
const num = Number(readline())
console.log(transfer(num))
全部评论

相关推荐

头像
10-09 19:35
门头沟学院 Java
洛必不可达:java的竞争激烈程度是其他任何岗位的10到20倍
点赞 评论 收藏
分享
杨柳哥:这不是普通人,那这个钱的是天才
点赞 评论 收藏
分享
10 1 评论
分享
牛客网
牛客企业服务