Skip to content

Instantly share code, notes, and snippets.

@asd1245dss
Created May 29, 2019 03:01
Show Gist options
  • Save asd1245dss/01d37ce875e93a00df47f5d4f553bd0b to your computer and use it in GitHub Desktop.
Save asd1245dss/01d37ce875e93a00df47f5d4f553bd0b to your computer and use it in GitHub Desktop.
public static int romanToInt(String s) {
int[] numArray = new int[26];
numArray['I' - 'A'] = 1;
numArray['V' - 'A'] = 5;
numArray['X' - 'A'] = 10;
numArray['L' - 'A'] = 50;
numArray['C' - 'A'] = 100;
numArray['D' - 'A'] = 500;
numArray['M' - 'A'] = 1000;
int pre = 0;
int current;
int result = 0;
char[] charArray = s.toCharArray();
for (char str : charArray) {
current = numArray[str - 'A'];
if (pre > 0 && pre < current) {
result = result - pre - pre;
}
pre = current;
result = result + current;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment