DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

3 1

LeetCode "12. Integer to Roman"

12. Integer to Roman

class Solution:
    def intToRoman(self, num: int) -> str:

        if num == 0:
            return ''

        symbols = [('I', 'V'), ('X', 'L'), ('C', 'D'), ('M')]
        roman = ''        
        numOfDigit = 0

        while num > 0:
            c = ''
            digit = num % 10

            if digit == 4:
                c = symbols[numOfDigit][0] + symbols[numOfDigit][1]
            elif digit == 9:
                c = symbols[numOfDigit][0] + symbols[numOfDigit + 1][0]
            else:
                if digit > 4:
                    c = symbols[numOfDigit][1]
                for i in range(digit % 5):
                    c += symbols[numOfDigit][0]

            # next digit
            num //= 10
            numOfDigit += 1

            roman = c + roman            

        return roman
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay