/*
* Given a roman numeral, convert it to an integer.
* Input is guaranteed to be within the range from 1 to 3999.
*
* */
public int romanToInt(String s) {
// transform to char array
char[] chars = s.toCharArray();
int sum = 0;
// corner case
if (chars.length == 0)
return sum;
// use slow and fast pointer
int slow = 0;
int fast = 1;
int preSum = 0;
// while loop the char array
while (fast < chars.length) {
preSum += getNum(chars[slow]);
// meet the peak
if (getNum(chars[fast]) > getNum(chars[slow]))
preSum = -preSum;
// meet the valley
if (getNum(chars[fast]) < getNum(chars[slow])) {
sum += preSum;
preSum = 0;
}
slow++;
fast++;
}
// get the result
sum += preSum + getNum(chars[slow]);
return sum;
}
public int getNum(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;
}
}
/*
* 感觉题目出的并不很清楚
* 应该给出对应方法
* 应该说明说否会出现XXCX这种情况
* 这种方法正好适应当前题目的维度
*
* */
public static int romanToInt2(String s) {
int nums[]=new int[s.length()];
for(int i=0;i<s.length();i++){
switch (s.charAt(i)){
case 'M':
nums[i]=1000;
break;
case 'D':
nums[i]=500;
break;
case 'C':
nums[i]=100;
break;
case 'L':
nums[i]=50;
break;
case 'X' :
nums[i]=10;
break;
case 'V':
nums[i]=5;
break;
case 'I':
nums[i]=1;
break;
}
}
int sum=0;
for(int i=0;i<nums.length-1;i++){
if(nums[i]<nums[i+1])
sum-=nums[i];
else
sum+=nums[i];
}
return sum+nums[nums.length-1];
}