1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.demo.s13;
import java.util.HashMap; import java.util.Map;
public class Solution { Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); }};
public int romanToInt(String s) { int ans = 0; int n = s.length(); for (int i = 0; i < n; ++i) { int value = symbolValues.get(s.charAt(i)); if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) { ans -= value; } else { ans += value; } } return ans; } }
|