规则如下
image.png限制
本次实现了3999及以下的数字转换。
具体代码
function convert(num) {
//最大数字是3999,且为整数
var romanNum = ['I','V','X','L','C','D','M'];
var strNum = String(num);
var arrNum = strNum.split("");
var len = arrNum.length;
var roman = '';
for (var i = 0; i < len; i++) {
var everyNum = Number(arrNum[i]);
if (everyNum < 4) {
for(var j = 0; j < Number(arrNum[i]); j++) {
roman += romanNum[(len-i-1)*2];
}
} else if (everyNum === 4) {
roman += romanNum[(len-i-1)*2] + romanNum[(len-i-1)*2+1];
} else if (everyNum === 5) {
roman += romanNum[(len-i-1)*2+1];
} else if (everyNum > 5 && everyNum <= 8) {
roman += romanNum[(len-i-1)*2+1];
for(var k = 0; k < Number(arrNum[i]) - 5; k++) {
roman += romanNum[(len-i-1)*2];
}
} else if (everyNum === 9) {
roman += romanNum[(len-i-1)*2] + romanNum[(len-i)*2];
}
}
return roman;
}
convert(9);
待改进
功能是实现了,但代码过于繁琐。。。一点都不优雅
网友评论