之前在练习freeCodeCamp上的题目遇到问题,想请问大家。
po错版麻烦请告知。
freeCodeCamp的题目是数字转罗马字。
我的程式如下:
var symbolCount = 0;
var rNum = 0;
var romanNStr = ""; //组出的罗马数字
function convertToRoman(num) {
rNum= num;
//先算开头M的个数
symbolCount = Math.floor(rNum/1000);
rNum = rNum -(1000*symbolCount);
for(var i = 0; i < symbolCount; i++ ){
romanNStr+="M";
}
calSymbol("M", "D", "C", 100);
calSymbol("C", "L", "X", 10);
calSymbol("X", "V", "I", 1);
return romanNStr;
}
//以三个为一组计算
function calSymbol(b, m, s, val){
symbolCount = Math.floor(rNum / val);
if(symbolCount == 9){
romanNStr += s + b;
rNum -= (9*val);
symbolCount = 0;
}
if(symbolCount == 4){
romanNStr += s + m;
rNum -= (4*val);
symbolCount = 0;
}
if(symbolCount >= 5){
romanNStr += m;
rNum -= (5 * val);
symbolCount -= 5;
}
for(var i = 0; i < symbolCount ; i++){
romanNStr += s;
rNum -= (1 * val);
}
}
================================
我知道我的程式不是最佳解,
但执行freeCodeCamp提供的[Run tests]按钮,仅有converToRoman(2)过关。
我自己也找不到问题,
麻烦高手跟我说我的程式哪里有问题,谢谢
freeCodeCamp的test如下
convertToRoman(2) should return "II".
convertToRoman(3) should return "III".
convertToRoman(4) should return "IV".
convertToRoman(5) should return "V".
convertToRoman(9) should return "IX".
convertToRoman(12) should return "XII".
convertToRoman(16) should return "XVI".
convertToRoman(29) should return "XXIX".
convertToRoman(44) should return "XLIV".
convertToRoman(45) should return "XLV"
convertToRoman(68) should return "LXVIII"
convertToRoman(83) should return "LXXXIII"
convertToRoman(97) should return "XCVII"
convertToRoman(99) should return "XCIX"
convertToRoman(500) should return "D"
convertToRoman(501) should return "DI"
convertToRoman(649) should return "DCXLIX"
convertToRoman(798) should return "DCCXCVIII"
convertToRoman(891) should return "DCCCXCI"
convertToRoman(1000) should return "M"
convertToRoman(1004) should return "MIV"
convertToRoman(1006) should return "MVI"
convertToRoman(1023) should return "MXXIII"
convertToRoman(2014) should return "MMXIV"
convertToRoman(3999) should return "MMMCMXCIX"