1 Topics:
Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Hide TagsMath String2 ideas: After I studied Wikipedia's instructions https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97, I found the rules to be complex, as follows:
- 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.
- The smaller Roman numerals on the left of the larger Roman numerals indicate that large numbers decrease the numbers.
- The left-minus number is limited to I, X, and C. For example, 45 can not be written as VL, only XLV
- However, the left subtraction cannot span a single digit. For example, 99 cannot be represented by an IC (), but by XCIX (). (equivalent to each digit of the Arabic numerals.) )
- The left minus number must be one, such as 8 written in VIII, not IIX.
- The right plus number cannot be more than three consecutive digits, such as 14 for XIV rather than XIIII. (See "Digital Restrictions" below.) )
- Add line by thousand:
- By adding a horizontal line or a subscript to the Roman numerals, it means multiplying this number by 1000, which is 1000 times times the original number.
- Similarly, if there are two horizontal lines above, it is 1000000 () times the original number.
- Digital Restrictions:
- The same digital can only appear at most three times, such as 40 can not 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.
It's too hard to if-else the range. Well, as a result I look at other people's answers and can directly
bitwiseTo determine the Roman numerals. (Wikipedia does not say it can be converted.) ) Https://leetcode.com/discuss/32626/simple-solution 3 Code:
Public String Inttoroman (int num) { = {"", "M", "MM", "MMM"}; = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; return M[NUM/1000] + c[(num%1000)/100] + x[(num%100)/10] + v[num%10]; }
[Leetcode 12] Inter to Roman