1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
class { public static int romanToInt(String s) { int result = 0;
char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == 'I') { if ((i + 1) < chars.length && chars[i + 1] == 'V') { result += 4; i++; continue; } else if ((i + 1) < chars.length && chars[i + 1] == 'X') { result += 9; i++; continue; } result += 1; }
if (chars[i] == 'X') { if ((i + 1) < chars.length && chars[i + 1] == 'L') { result += 40; i++; continue; } else if ((i + 1) < chars.length && chars[i + 1] == 'C') { result += 90; i++; continue; } result += 10; }
if (chars[i] == 'C') { if ((i + 1) < chars.length && chars[i + 1] == 'D') { result += 400; i++; continue; } else if ((i + 1) < chars.length && chars[i + 1] == 'M') { result += 900; i++; continue; } result += 100; }
if (chars[i] == 'V') result += 5; if (chars[i] == 'L') result += 50; if (chars[i] == 'D') result += 500; if (chars[i] == 'M') result += 1000; } return result; } }
|
近期评论