Medium Roman to Integer
40%
Accepted
Given a roman numeral, convert it to an integer.
The answer is guaranteed to be within the range from 1 to 3999.
Have you met this question in a real interview?
Yes
Example
IV
-> 4
XII
-> 12
XXI
-> 21
XCIX
-> 99
Clarification
What is Roman Numeral?
- https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- http://baike.baidu.com/view/42061.htm
public class Solution {
/**
* @param s Roman representation
* @return an integer
*/
public int romanToInt(String s) {
// Write your code here
if(s == null || s.length() == 0){
return 0;
}
int pre = charToInt(s.charAt(0));
int res = 0;
for(int i = 1; i < s.length(); i++){
int cur = charToInt(s.charAt(i));
if(pre >= cur){
res += pre;
} else {
res -= pre;
}
pre = cur;
}
res += pre;
return res;
}
private int charToInt(char a){
switch(a){
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;
}
return 0;
}
}
No comments:
Post a Comment