Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 8, 2013 07:11
Show Gist options
  • Select an option

  • Save luoxiaoxun/5946785 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5946785 to your computer and use it in GitHub Desktop.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
C++:
class Solution {
public:
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ret=0;
for(int i=0;i<s.size();i++){
if(i<s.size()-1){
if(getVal(s[i])<getVal(s[i+1])) ret -=getVal(s[i]);
else ret +=getVal(s[i]);
}else ret +=getVal(s[i]);
}
return ret;
}
int getVal(char c){
switch(c){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
};
Java:
public class Solution {
public int romanToInt(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int ret=0;
for(int i=0;i<s.length();i++){
if(i<s.length()-1){
if(getVal(s.charAt(i))<getVal(s.charAt(i+1))) ret -=getVal(s.charAt(i));
else ret +=getVal(s.charAt(i));
}else ret +=getVal(s.charAt(i));
}
return ret;
}
public int getVal(char c){
switch(c){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment