暴力破解(if循环)解决leetcode数字转成罗马数字

1.题目描述
暴力破解(if循环)解决leetcode数字转成罗马数字_第1张图片
2.解题思路
刚看到这个题目的时候,感觉说的有点啰嗦,其实不难发现,这个题目和之前的给你多少钱,什么2元,5元的,给你一个数字,让你算各种钱币有多少张。无非就是从小到大进行判断,首先判断给定的数字,能容纳多少个最大的,然后依次减少。
3.代码实现

class Solution:
    def intToRoman(self, num: int) -> str:
        str1 = ""
        while num != 0:
            print("num",num)
            if int(num / 1000):
                num1 = int(num / 1000)
                for i in range(0, num1):
                    str1 = str1 + "M"
                num = num - num1 * 1000
            elif int(num / 900):
                num1 = int(num / 900)
                for i in range(0, num1):
                    str1 = str1 + "CM"
                num = num - num1 * 900
            elif int(num / 500):
                num1 = int(num / 500)
                for i in range(0, num1):
                    str1 = str1 + "D"
                num = num - num1 * 500
            elif int(num / 400):
                num1 = int(num / 400)
                for i in range(0, num1):
                    str1 = str1 + "CD"
                num = num - num1 * 400
            elif int(num / 100):
                num1 = int(num / 100)
                for i in range(0, num1):
                    str1 = str1 + "C"
                num = num - num1 * 100
            elif int(num / 90):
                num1 = int(num / 90)
                for i in range(0, num1):
                    str1 = str1 + "XC"
                num = num - num1 * 90
            elif int(num / 50):
                num1 = int(num / 50)
                for i in range(0, num1):
                    str1 = str1 + "L"
                num = num - num1 * 50
            elif int(num / 40):
                num1 = int(num / 40)
                for i in range(0, num1):
                    str1 = str1 + "XL"
                num = num - num1 * 40
            elif int(num / 10):
                num1 = int(num / 10)
                for i in range(0, num1):
                    str1 = str1 + "X"
                num = num - num1 * 10
            elif int(num / 9):
                num1 = int(num / 9)
                for i in range(0, num1):
                    str1 = str1 + "IX"
                num = num - num1 * 9

            elif int(num / 5):
                num1 = int(num / 5)
                for i in range(0, num1):
                    str1 = str1 + "V"
                num = num - num1 * 5
            elif int(num / 4):
                num1 = int(num / 4)
                for i in range(0, num1):
                    str1 = str1 + "IV"
                num = num - num1 * 4
            elif int(num / 1):
                num1 = int(num / 1)
                for i in range(0, num1):
                    str1 = str1 + "I"
                num = num - num1 * 1
        return str1
            

                

你可能感兴趣的:(leetcode,算法,python,数据结构)