Problem:
Given an integer, convert it to a Roman numeral. Input is guaranteed to being within the range from 1 to 3999.
Converts an integer of 1-3999 to Roman numerals
Thinking:
(1)
comparison example
Single Digit Example
ⅰ,1 "Ⅱ. 2 "ⅲ,3" ⅳ,4 "Ⅴ. 5 "ⅵ,6" Ⅶ. 7 "ⅷ,8" Ⅸ. 9 "
Example of 10 digits
Ⅹ. 10 "ⅺ,11" ⅻ,12 "xiii,13" xiv,14 "xv,15" xvi,16 "xvii,17" xviii,18 "xix,19" xx,20 "xxi,21" xxii,22 "xxix,29" XXX,30 "XXXIV, 34 "xxxv,35" xxxix,39 "xl,40" l,50 "li,51" lv,55 "lx,60" lxv,65 "lxxx,80" xc,90 "xciii,93" xcv,95 "xcviii,98" XCIX,99 "
Examples of hundred
c,100 "cc,200" ccc,300 "cd,400" d,500 "dc,600" dcc,700 "dccc,800" cm,900 "cmxcix,999"
Thousands of examples
m,1000 "mc,1100" mcd,1400 "md,1500" mdc,1600 "mdclxvi,1666" mdccclxxxviii,1888 "mdcccxcix,1899" MCM,1900 "MCMLXXVI,1976 "mcmlxxxiv,1984" mcmxc,1990 "mm,2000" mmmcmxcix,3999 "
(2) The technique of avoiding N-Multi-conditional inference: Using the laws of Roman numerals themselves. Subtract a cardinality. To simplify complexity
Code
Class Solution {public: string inttoroman (int num) { 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"}; string result; for (int i = 0, I < i++) {while (num >= values[i]) {num- = values[i]; Result.append (Numerals[i]); } } return result;} ;
Leetcode ways to solve problems | | Integer to Roman problem