gpt4 book ai didi

javascript - 在 JavaScript 中将数字转换为罗马数字

转载 作者:IT王子 更新时间:2023-10-29 02:59:51 26 4
gpt4 key购买 nike

如何将整数转换为 roman numerals

function romanNumeralGenerator (int) {

}

例如,请参阅以下示例输入和输出:

1 = "I"
5 = "V"
10 = "X"
20 = "XX"
3999 = "MMMCMXCIX"

注意:只支持 1 到 3999 之间的数字

最佳答案

我在这个博客上使用 google 发现了一个不错的博客:

http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter

function romanize (num) {
if (isNaN(num))
return NaN;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
}

关于javascript - 在 JavaScript 中将数字转换为罗马数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9083037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com