Roman to Integer
此题的关键在于减的情况只有以下几种:IV/IX/XL/XC/CD/CM
因此在count时若出现这六种情况,先全部算作加的情况,最后再减去两倍的多余部分
public class Solution {
public int romanToInt(String s) {
int sum = 0;
if(s.indexOf("IV")!=-1)
sum = sum -2;
if(s.indexOf("IX")!=-1)
sum = sum -2;
if(s.indexOf("XL")!=-1)
sum = sum -20;
if(s.indexOf("XC")!=-1)
sum = sum -20;
if(s.indexOf("CD")!=-1)
sum = sum -200;
if(s.indexOf("CM")!=-1)
sum = sum -200;
for(int i = 0;i < s.length();i++)
{
char ch = s.charAt(i);
if(ch =='I')
sum = sum+1;
else if(ch =='V')
sum = sum+5;
else if(ch =='X')
sum = sum+10;
else if(ch =='L')
sum = sum+50;
else if(ch =='C')
sum = sum+100;
else if(ch =='D')
sum = sum+500;
else
sum=sum+1000;
}
return sum;
}
}