Open zilongxuan001 opened 6 years ago
此题有些烧脑,于是分解如下 num=36 1.for循环index=8时:
(1)10<=36成立,执行while循环:
romanized=X;
num=36-10=26;
(2)10<=26 成立,执行while循环:
romanized=XX;
num=26-10=16;
(3)10<=16成立,执行while循环;
romanized=XXX;
num=16-10=6;
(4)10>6不成立,跳出while循环。
2.for循环 index=9
9<=6,不成立,跳出while循环;
5<=6成立,执行while循环: romanzid=V; num=6-5=1;
源代码
var convertToRoman = function(num) {
var decimalValue = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
var romanNumeral = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
var romanized = '';
for (var index = 0; index < decimalValue.length; index++) {
while (decimalValue[index] <= num) {
romanized += romanNumeral[index];
num -= decimalValue[index];
}
}
return romanized;
}
// test here
convertToRoman(36);
功能
将十进制数字转化为罗马数字。
代码
效果
参考
JavaScript splice() 方法 JavaScript join() 方法 Roman Numerals
来源: https://www.freecodecamp.org/challenges/roman-numeral-converter