做好分类,注意边界。
Success
Runtime: 52 ms, faster than 98.97% of Python3 online submissions forInteger to Roman.
Memory Usage: 13.3 MB, less than 60.15% of Python3 online submissions for Integer to Roman.
Submission Detail
3999 / 3999 test cases passed. | Status: Accepted |
Runtime: 52 ms Memory Usage: 13.3 MB | Submitted: 0 minutes ago |
class Solution: def intToRoman(self, num: int) -> str: if 1000 <= num <= 3999: units_digit = num % 10 tens_digit = num % 100 - units_digit hundreds_digit = num%1000 - tens_digit - units_digit thousands_digit = num //1000 units_ret = Solution().dealunitsdigit(units_digit) tens_ret = Solution().dealtensdigit(tens_digit) hundreds_ret = Solution().dealhundredsdigit(hundreds_digit) thousands_ret = "" for index in range(thousands_digit): thousands_ret = thousands_ret + "M" return thousands_ret + hundreds_ret + tens_ret + units_ret elif 100 <= num < 1000: units_digit = num %10 tens_digit = num%100 - units_digit hundreds_digit = num - tens_digit - units_digit units_ret = Solution().dealunitsdigit(units_digit) tens_ret = Solution().dealtensdigit(tens_digit) hundreds_ret = Solution().dealhundredsdigit(hundreds_digit) return hundreds_ret + tens_ret + units_ret elif 10 <= num < 100: units_digit = num %10 tens_digit = num - units_digit units_ret = Solution().dealunitsdigit(units_digit) tens_ret = Solution().dealtensdigit(tens_digit) return tens_ret + units_ret elif 1 <= num < 10: ret = Solution().dealunitsdigit(num) return ret #1-9 def dealunitsdigit(self,num:int) -> str: if num == 0: return "" if num == 4: return "IV" if num == 9: return "IX" if num <5: ret ="" for index in range(num): ret = ret + "I" return ret else: ret ="V" for index in range(num -5): #min V ret = ret + "I" return ret #10,20,30,40...90 def dealtensdigit(self,num:int) -> str: if num == 40: return "XL" if num == 90: return "XC" if num <50: ret ="" for index in range(num//10): ret = ret + "X" return ret else: ret ="L" for index in range((num -50)//10): #min L ret = ret + "X" return ret #100,200,300...900 def dealhundredsdigit(self,num:int) -> str: if num == 400: return "CD" if num == 900: return "CM" if num <500: ret ="" for index in range(num//100): ret = ret + "C" return ret else: ret ="D" for index in range((num -500)//100): #min L ret = ret + "C" return ret