题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:
根据规则1,2,3
具体代码如下:
public class Solution {
public int romanToInt(String s) {
char[] s_copy = s.toCharArray();
int len = s.length();
int flag = 1;
int result = 0;
for(int i = len-1; i>0; i--){
int nums1 = getValues(s_copy[i]);
int nums2 = getValues(s_copy[i-1]);
nums1 = nums1*flag;
if(nums1 > nums2){
flag = -1;
}else{
flag = 1;
}
result = result + nums1;
}
return result + getValues(s_copy[0])*flag;
}
public int getValues(char c){
if(c == 'I')
return 1;
if(c == 'V')
return 5;
if(c == 'X')
return 10;
if(c == 'L')
return 50;
if(c == 'C')
return 100;
if(c == 'D')
return 500;
else //c == 'M'
return 1000;
}
}