Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int romanToInt(String s) {
- Map<Character, Integer> romanToInteger = Map.of(
- 'I', 1,
- 'V', 5,
- 'X', 10,
- 'L', 50,
- 'C', 100,
- 'D', 500,
- 'M', 1000
- );
- int result = 0;
- for (int i = 0; i < s.length(); i++) {
- Character c = s.charAt(i);
- Character cNext = Character.MIN_VALUE;
- boolean shouldSubtract = false;
- if (i+1 < s.length()) {
- cNext = s.charAt(i+1);
- switch(c) {
- case 'I':
- if (cNext == 'V' || cNext == 'X') {
- shouldSubtract = true;
- }
- break;
- case 'X':
- if (cNext == 'L' || cNext == 'C') {
- shouldSubtract = true;
- }
- break;
- case 'C':
- if (cNext == 'D' || cNext == 'M') {
- shouldSubtract = true;
- }
- break;
- }
- }
- if (shouldSubtract) {
- result += (romanToInteger.get(cNext) - romanToInteger.get(c));
- i++;
- }
- else {
- result += romanToInteger.get(c);
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement