之前在練習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"