每日一题 2019 - 03 - 04
题目:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
1 | Symbol Value |
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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(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.
Example 1:
1 | Input: 3 |
Example 2:
1 | Input: 4 |
Example 3:
1 | Input: 9 |
Example 4:
1 | Input: 58 |
Example 5:
1 | Input: 1994 |
思路:
这个题让我们将阿拉伯数字转成罗马数字,其实就跟以前做过的一个把阿拉伯数字转成中文写法是一样的,就是找出具体的对应关系,并且叠加在一起就好了,比如:
- 千位,1000为
M
,2000为MM
,3000为MMM
- 百位,100-900对应
C
,CC
,CCC
,CD
,D
,DC
,DCC
,DCCC
,CM
等;找到对应关系我们就可以成功解决这个题。
代码:
1 | class Solution { |