Skip to content

Instantly share code, notes, and snippets.

@tuanna-hsp
Created February 16, 2020 00:18
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 tuanna-hsp/6880d51f28a6c253c3726cce026e771f to your computer and use it in GitHub Desktop.
Save tuanna-hsp/6880d51f28a6c253c3726cce026e771f to your computer and use it in GitHub Desktop.
Roman to integer
class Solution {
private int symbolValue(char ch) {
switch (ch) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
return 0;
}
public int romanToInt(String s) {
int result = 0;
int lastValue = 0;
char[] chars = s.toCharArray();
for (int i = chars.length - 1; i >= 0; i--) {
int value = symbolValue(chars[i]);
if (value < lastValue) {
result -= value;
} else {
result += value;
}
lastValue = value;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment