Skip to content

Instantly share code, notes, and snippets.

@rdtr
Last active January 5, 2016 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdtr/99d9cec8c7831df021d1 to your computer and use it in GitHub Desktop.
Save rdtr/99d9cec8c7831df021d1 to your computer and use it in GitHub Desktop.
algorithm_math_romanr_to_integer.java
public class Solution {
public int romanToInt(String s) {
int len = s.length();
s = s + " ";
int res = 0;
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
char nxCh = s.charAt(i+1);
if (ch == 'M') {
res += 1000;
} else if (ch == 'C') {
if (nxCh == 'M') {
res += 900;
i++;
} else if (nxCh == 'D') {
res += 400;
i++;
} else {
res += 100;
}
} else if (ch == 'D') {
res += 500;
} else if (ch == 'X') {
if (nxCh == 'C') {
res += 90;
i++;
} else if (nxCh == 'L') {
res += 40;
i++;
} else {
res += 10;
}
} else if (ch == 'L') {
res += 50;
} else if (ch == 'I') {
if (nxCh == 'X') {
res += 9;
i++;
} else if (nxCh == 'V') {
res += 4;
i++;
} else {
res++;
}
} else { // if (ch == 'V')
res += 5;
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment