13. 罗马数字转整数
一、Java
import java.util.HashMap;class Solution {public int romanToInt(String s) {HashMap<Character, Integer> m = new HashMap<>() {{put('I', 1);put('V', 5);put('X', 10);put('L', 50);put('C', 100);put('D', 500);put('M', 1000);}};char[] a = s.toCharArray();int sum = m.get(a[0]);for (int i = 1; i < a.length; i++) {sum += m.get(a[i]);if (m.get(a[i - 1]) < m.get(a[i])) sum -= m.get(a[i - 1]) * 2;}return sum;}
}
二、C++
#include <string>
#include <unordered_map>using namespace std;class Solution {
public:int romanToInt(string s) {unordered_map<char, int> m = {{'I', 1},{'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500},{'M', 1000}};int sum = m[s[0]];for (int i = 1; i < s.length(); i++) {sum += m[s[i]];if (m[s[i - 1]] < m[s[i]]) sum -= m[s[i - 1]] * 2;}return sum;}
};
三、Python
class Solution:def romanToInt(self, s: str) -> int:m = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}sum = m[s[0]]for i in range(1, len(s)):sum += m[s[i]]if m[s[i - 1]] < m[s[i]]:sum -= m[s[i - 1]] * 2return sum
四、JavaScript
var romanToInt = function (s) {let m = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};let sum = m[s[0]];for (i = 1; i < s.length; i++) {sum += m[s[i]];if (m[s[i - 1]] < m[s[i]])sum -= m[s[i - 1]] * 2;}return sum;
};
五、Go
package mainfunc romanToInt(s string) int {m := map[uint8]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}sum := m[s[0]]for i := 1; i < len(s); i++ {sum += m[s[i]]if m[s[i-1]] < m[s[i]] {sum -= m[s[i-1]] * 2}}return sum
}