DEV Community

loading...

Integer to Roman and back

jpantunes profile image JP Antunes ・2 min read

I haven't posted in a while and now that my career took a U-turn back into the boardroom, I suppose it might be the beginning of the end of my coding days... again. Strange times!

While on the topic of switching back and forth between worlds, here's two simple O(n) solutions to Leetcode's Roman to Integer and Integer to Roman problems.

// integer to roman numeral
const intToRoman = function(num) {
    const rosettaStone = {
        1: 'I',
        5: 'V',
        10: 'X',
        50: 'L',
        100: 'C',
        500: 'D',
        1000: 'M'
    };            
    let resStr = '';

    for (let i = 1000; i >= 1; i /= 10) {
        const times = Math.trunc(num / i);
        if (times > 0) {
            if (times % 9 == 0) {
                resStr += rosettaStone[i]
                    .concat(rosettaStone[(times + 1) * i])    
            } else if (times % 8 == 0) {
                resStr += rosettaStone[(times - 3) * i]
                    .concat(rosettaStone[(times - 7) * i]
                    .repeat(3))
            } else if (times % 7 == 0) {
                resStr += rosettaStone[(times - 2) * i]
                    .concat(rosettaStone[(times - 6) * i]
                    .repeat(2))                
            } else if (times % 6 == 0) {
                resStr += rosettaStone[(times - 1) * i]
                    .concat(rosettaStone[i])
            } else if (times % 5 == 0) {
                resStr += rosettaStone[(times) * i] 
            } else if (times % 4 == 0) {
                resStr += rosettaStone[i]
                    .concat(rosettaStone[(times + 1) * i])   
            } else if (times <= 3) {
                resStr += rosettaStone[i].repeat(times);            
            } 
            num -= times * i;
        } 
    }        

    return resStr;            
};

// roman numeral to integer
const romanToInt = function(s) {
    const rosettaStone = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000        
    };
    let result = 0;
    let lastValue = 0;

    for (let i = s.length -1; i >= 0; i--) {
        const value = rosettaStone[s[i]];
        if (lastValue > value) {
            result -= value;
        } else {
            result += value;
        }
        lastValue = value;
    }

    return result;
};

optional soundtrack

Discussion (1)

pic
Editor guide
Collapse
mohsenalyafei profile image
Mohsen Alyafei

Great. Thanks.