题目描述:
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 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 a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
汉语理解:将罗马字母表示的数字转换为阿拉伯数字,不过其中有几种特例表示,如4,9,40,90,400,900这几个数组表示是另外的方法。
解题思路:使用最简单的思路每两个字符作为一个单位进行比较,若为IV,IX,XL,XC,CD,CM则直接处理,其余的则每位后移处理。代码如下,其中IXVCDM等代表的数字可以使用map来存储,不过在代码中我未使用这种存储方法(代码最直观的写出来后就懒了,没有重构)。
代码(java):
class Solution {
public int romanToInt(String s) {
int res=0;
int i=0;
for(i=0;i<s.length()-1;i++){
if(s.charAt(i)=='I' && s.charAt(i+1)=='V'){
res+=4;
i+=1;
}
else if(s.charAt(i)=='I' && s.charAt(i+1)=='X'){
res+=9;
i+=1;
}
else if(s.charAt(i)=='X' && s.charAt(i+1)=='L'){
res+=40;
i+=1;
}
else if(s.charAt(i)=='X' && s.charAt(i+1)=='C'){
res+=90;
i+=1;
}
else if(s.charAt(i)=='C' && s.charAt(i+1)=='D'){
res+=400;
i+=1;
}
else if(s.charAt(i)=='C' && s.charAt(i+1)=='M'){
res+=900;
i+=1;
}
else if(s.charAt(i)=='I'){
res+=1;
}
else if(s.charAt(i)=='V'){
res+=5;
}
else if(s.charAt(i)=='X'){
res+=10;
}
else if(s.charAt(i)=='L'){
res+=50;
}
else if(s.charAt(i)=='C'){
res+=100;
}
else if(s.charAt(i)=='D'){
res+=500;
}
else if(s.charAt(i)=='M'){
res+=1000;
}
}
if(i<s.length()){
if(s.charAt(i)=='I'){
res+=1;
}
else if(s.charAt(i)=='V'){
res+=5;
}
else if(s.charAt(i)=='X'){
res+=10;
}
else if(s.charAt(i)=='L'){
res+=50;
}
else if(s.charAt(i)=='C'){
res+=100;
}
else if(s.charAt(i)=='D'){
res+=500;
}
else if(s.charAt(i)=='M'){
res+=1000;
}
}
return res;
}
}