Last active
December 11, 2015 18:59
-
-
Save guolinaileen/4645546 to your computer and use it in GitHub Desktop.
'M', 1000; 'D', 500; 'C', 100 ; 'L', 50; 'X',10; 'V', 5; 'I', 1 右加左减:
在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
但是,左减时不可跨越一个位数。比如,99不可以用IC()表示,而是用XCIX()表示。(等同于阿拉伯数字每位数字分别表示。)
此外,左减数字必须为一位,比如8写成VIII,而非IIX。
同理,右加数字不可超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)
加线乘千:
在罗马数字的上方加上一条横线或者加上下标的Ⅿ,表示将这个数…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int romanToInt(string s) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(s.length()==0) return 0; | |
map<char, int> mp; | |
mp['M']=1000; | |
mp['D']=500; | |
mp['C']=100; | |
mp['L']=50; | |
mp['X']=10; | |
mp['V']=5; | |
mp['I']=1; | |
int sum=mp[s[s.length()-1]]; | |
for(int i=s.length()-2; i>=0; i--) | |
{ | |
if(mp[s[i+1]]>mp[s[i]]) sum-=mp[s[i]]; | |
else sum+=mp[s[i]]; | |
} | |
return sum; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Solution { | |
public int romanToInt(String s) { | |
if(s=="") return 0; | |
int length=s.length(); | |
char [] array=s.toCharArray(); | |
int result=0; | |
Hashtable<Character, Integer> table=new Hashtable<Character, Integer>(); | |
table.put('M', 1000); | |
table.put('D', 500); | |
table.put('C', 100); | |
table.put('L', 50); | |
table.put('X', 10); | |
table.put('V', 5); | |
table.put('I', 1); | |
for(int i=0; i<length; i++) | |
{ | |
if(array[i]=='M' || array[i]=='D' ||array[i]=='L'||array[i]=='V') | |
{ | |
result+=table.get(array[i]); | |
continue; | |
} | |
if((i+1)<length) | |
{ | |
if(array[i]=='C' && (array[i+1]=='M' || array[i+1]=='D')) | |
{ | |
result-=100; | |
continue; | |
} | |
if(array[i]=='X' && (array[i+1]=='C' || array[i+1]=='L')) | |
{ | |
result-=10; | |
continue; | |
} | |
if(array[i]=='I' && (array[i+1]=='V' || array[i+1]=='X')) | |
{ | |
result-=1; | |
continue; | |
} | |
} | |
result+=table.get(array[i]); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment