lc13 Roman to Integer
Six kinds of encounters that special circumstances are -2, -20, -200,
According to the rules of Roman numerals, each may only occur once. So one need only consider the use indexOf () to determine whether these types of special circumstances arise
Then traverse s, as defined for each character, value can be combined with
1 class Solution { 2 public int romanToInt(String s) { 3 int res = 0; 4 5 if(s.indexOf("IV") != -1) 6 res -= 2; 7 if(s.indexOf("IX") != -1) 8 res -= 2; 9 if(s.indexOf("XL") != -1) 10 res -= 20; 11 if(s.indexOf("XC") != -1) 12 res -= 20; 13 if(s.indexOf("CD") != -1) 14 res -= 200; 15 if(s.indexOf("CM") != -1) 16 res -= 200; 17 18 19 for(char i : s.toCharArray()){ 20 if(i == 'I') 21 res += 1; 22 if(i == 'V') 23 res += 5; 24 if(i == 'X') 25 res += 10; 26 if(i == 'L') 27 res += 50; 28 if(i == 'C') 29 res += 100; 30 if(i == 'D') 31 res += 500; 32 if(i == 'M') 33 res += 1000; 34 } 35 36 37 38 39 return res; 40 } 41 }