Created
July 6, 2022 10:52
-
-
Save riyafa/b8ae16ab3331f5ab7db9d3cc1ee59e8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 RomanToInteger { | |
public int romanToInt(String s) { | |
int prev = 0; | |
int result = 0; | |
for(int i = s.length() -1; i >= 0; i--) { | |
char cur = s.charAt(i); | |
int curVal = getInteger(cur); | |
if(curVal < prev) { | |
result -= curVal; | |
} else { | |
result += curVal; | |
} | |
prev = curVal; | |
} | |
return result; | |
} | |
private int getInteger(char c) { | |
switch(c) { | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment