###### tags: `leetcode` # 12. Integer to Roman ## my code ```python= class Solution: def intToRoman(self, num: int) -> str: s = '' # not [] r1dict = {1:'I',10:'X',100:'C',1000:'M',10000:'only-to-prevent-KeyError'} r5dict = {1:'V',10:'L',100:'D',1000:'only-for-consistency'} for d in [1000,100,10,1]: # d is for decimal base r1 = r1dict[d] # roman digit for 1*d r5 = r5dict[d] # roman digit for 5*d r10 = r1dict[d*10] myDict = {0:'',1:r1, 2:r1*2,3:r1*3, 4:r1+r5, 5:r5,6:r5+r1, 7:r5+r1*2, 8:r5+r1*3, 9:r1+r10} x = num//d num = num - x * d s += myDict[x] # not s.append(myDict[x]) return s ``` ## another person’s ```java= public static String intToRoman(int num) { String M[] = {"", "M", "MM", "MMM"}; String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; } ``` ## another person’s ```java= public class Solution { public String intToRoman(int number) { int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] numerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; StringBuilder result = new StringBuilder(); for (int i = 0; i < values.length; i++) { while (number >= values[i]) { number -= values[i]; result.append(numerals[i]); } } return result.toString(); } } ``` ## another person’s, **zip()** ```python= class Solution(object): def intToRoman(self, num): dict = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] result = "" for letter, n in zip(dict, nums): result += letter * int(num / n) num %= n return result ``` ## another person’s ```python= def intToRoman1(self, num): values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] res, i = "", 0 while num: res += (num//values[i]) * numerals[i] num %= values[i] i += 1 return res ``` ## another person’s, **enumerate()?????** https://leetcode.com/problems/integer-to-roman/discuss/6304/Python-simple-solution. ```python= def intToRoman(self, num): values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] res = "" for i, v in enumerate(values): res += (num//v) * numerals[i] num %= v return res ``` ## another person’s, **zip()?????** https://leetcode.com/problems/integer-to-roman/discuss/6361/A-simple-python-code-easy-to-understand ```python= class Solution(object): def intToRoman(self, num): dict = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] result = "" for letter, n in zip(dict, nums): result += letter * int(num / n) num %= n return result ```