94 percentile less hardcoded javascript solution


  • 0
    M

    solution scalable in case roman numeral 5000 and 10000 is added. :)
    suggestion for improvement is always welcome.

    var intToRoman = function(num) {
        var dict = [ 1, 'I', 5, 'V', 10, 'X', 50, 'L', 100, 'C', 500, 'D', 1000, 'M' ];
        var result = "";
        var reducingDecimal = Math.pow(10, String(num).length - 1);
        
        while (reducingDecimal >= 1) {
            var currDigit = Math.floor(num / reducingDecimal);
            for (var i=0;i<dict.length;i+=4) {
                if (dict[i] === reducingDecimal) {
                    if (num >= 1000) {
                        result = dict[i+1].repeat(currDigit);
                    } else {
                        switch(currDigit) {
                            case 4:
                                result += dict[i+1] + dict[i+3];
                                break;
                            case 5:
                                result += dict[i+3];
                                break;
                            case 9:
                                result += dict[i+1] + dict[i+5];
                                break;
                            default:
                                if (currDigit > 5) {
                                    result += dict[i+3];
                                    currDigit -= 5;
                                }
                                result += dict[i+1].repeat(currDigit);
                                break;
                        }
                    }
                }
            }
            num %= reducingDecimal;
            reducingDecimal /= 10;
        }
        return result;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.