Created
February 16, 2020 00:18
-
-
Save tuanna-hsp/6880d51f28a6c253c3726cce026e771f to your computer and use it in GitHub Desktop.
Roman to integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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