天天看点

Leetcode 12. Integer to Roman12. Integer to Roman

12. Integer to Roman

题目描述

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
           

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. 
X can be placed before L (50) and C (100) to make 40 and 90. 
C can be placed before D (500) and M (1000) to make 400 and 900.
           

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

思路

仔细看一下其实三个字母对应一位十进制数字,比如I和V都是对应到个位上的数字,当然特殊的9是用IX来表示的。所以我们可以一位一位地分开处理整个十进制数。

首先取出个位数字x,然后判断跟x的大小,等于9就是

IX

,等于5就是一个

V

,大于5就在

V

的右边添加x-5个

I

,等于4就是

IV

,小于4就x个

I

x = { I X if  x = 9 V I . . . I ⎵ x-5 if  9 > x > 5 V if  x = 5 I V if  x = 4 I . . . I ⎵ x if  x < 4 x = \begin{cases} IX &\text{if } x = 9 \\ V \underbrace{I...I}_{\text{x-5}} &\text{if } 9 > x > 5 \\ V &\text{if } x = 5 \\ IV &\text{if } x = 4 \\ \underbrace{I...I}_{\text{x}} &\text{if } x < 4 \end{cases} x=⎩⎪⎪⎪⎪⎪⎪⎪⎪⎨⎪⎪⎪⎪⎪⎪⎪⎪⎧​IXVx-5

I...I​​VIVx

I...I​​​if x=9if 9>x>5if x=5if x=4if x<4​

如果换到十位数字就是把上表中的X、V、I换成C、L、X

然后百位数字就是换成M、D、C

千位数字只到3,就是说只可能是x个M

代码

版权声明:本文为CSDN博主「d4snap」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

                原文链接:https://blog.csdn.net/d4snap/article/details/83590237