public int romanToInt(String s) { int target=0; for(int i =0;i<s.length();i++) { if(s.charAt(i) == 'I') { if (i+1<s.length()&& (s.charAt(i+1)=='V'|| s.charAt(i+1)=='X')) { target-=1; } else { target+=1; } } if(s.charAt(i) == 'X') { if (i+1<s.length()&& (s.charAt(i+1)=='L'|| s.charAt(i+1)=='C')) { target-=10; } else { target+=10; } } if(s.charAt(i) == 'C') { if (i+1<s.length()&& (s.charAt(i+1)=='D'|| s.charAt(i+1)=='M')) { target-=100; } else { target+=100; } } if(s.charAt(i)=='V') { target+=5; } if(s.charAt(i)=='L') { target+=50; } if(s.charAt(i)=='D') { target+=500; } if(s.charAt(i)=='M') { target+=1000; } } return target; }
test code :
int x = one.romanToInt( "MCMXCIV"); System.out.println(x);