共计 533 个字符,预计需要花费 2 分钟才能阅读完成。
需求
把传入的数字转为罗马数字,所有罗马数字答案都应该大写。
罗马数字由 7 个基本字符组成:
I | V | X | L | C | D | M | V̅ |
1 | 5 | 10 | 50 | 100 | 500 | 1000 | 5000 |
代码实现
function convertToRoman(num) {let romanArr = []
const romanObj = {0: ['','I','II','III','IV','V','VI','VII','VIII','IX'],
1: ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC'],
2: ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM'],
3: ['','M','MM','MMM','I̅V̅','V̅','V̅I̅','V̅I̅I̅','V̅I̅I̅I̅','I̅X̅'],
}
const numArr = num
.toString()
.split('')
.map((item) => parseInt(item))
let m = numArr.length - 1
for (let n = m; n >= 0; n--) {romanArr.push(romanObj[n][numArr[m - n]])
}
return romanArr.join('')
}
正文完