Title:Given An integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Main topic:Enter an integer number, convert it to Roman numerals, and range between 1--3999. Ideas:before doing this question deliberately Google a little Roman figure is what ghosts, because previously only know the Roman numeral 1---10 (=, =), the wikipedia explanation paste as follows:
There are 7 Roman numerals, namely I (1), V (5), X (10), L (50), C (100), D (500) and M (1000). Any positive integer can be represented by the following rules. It is important to note that there is no "0" in the Roman numerals, regardless of the rounding system . Roman numerals are generally considered to be used only for counting , not for calculation.
- Repeat several times: a Roman number repeats several times, indicating several times the number.
- Right plus left minus:
- The smaller Roman numerals on the right side of the larger Roman numerals indicate large numbers plus small numbers.
-
-
- However, the left subtraction cannot span a single bit value. For example, 99 cannot be represented by an IC (), but by XCIX (). (equivalent to each digit of the Arabic numerals.) )
-
-
- add line by thousand:
-
- Similarly, if there are two horizontal lines above, That is 1000000 () times the original number.
- Digital Restrictions:
- The same digital can only appear three consecutive times, such as 40 cannot be represented as XXXX, but to be represented as XL.
- Exception: Since IV is the first word of the Roman mythology Lord Jupiter (ie, ivpiter, the Roman alphabet does not have J and u), it is sometimes substituted with IIII for IV.
know what is the Roman number is good to do, my idea is: anyway the largest number until 3999, simply build a table, will be 1--9, ten---90,---900,---3000 in accordance with the subscript corresponding to deposit into a two-dimensional array inside, and then each bit of the number of separate, look up the table , append to the result string. Code:
Class Solution {public: std::string inttoroman (int num) { std::string result = ""; std::string romannums[4][10] = { {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, {"", "X", "xx", "xx X "," XL "," L "," LX "," LXX "," LXXX "," XC "}, {" "," C "," CC "," CCC "," CD "," D "," DC "," DCC "," DCCC "," CM "}, {" "," M ", "MM", "MMM"} ; Remove the first three digits for (int i = n, j = 3; I! = 1; I/=,--j) { result + = romannums[j][num/i%]; } Take out the last digit of the number result + = romannums[0][num%]; return result;} ;
The fastest execution time for the above code in Leetcode is 36ms, but changing the two-dimensional array to char * is the fastest execution time is 24ms ... Description of C + + string here is no char* fast ah.
Reference: https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
Leetcode---Integer to Roman