DEV Community

JP Antunes
JP Antunes

Posted on

3

Integer to Roman and back

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei

Great. Thanks.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay