LeetCode 13 Roman to Integer (Rome to Integer)
Translation
Given a roman number, convert it to an integer value. The input value must be between 1 and 3999.
Original
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
I didn't have a good idea at the beginning. Although I can continue using the previous topic, the result is as follows ...... Messy code ......
public class Solution{ public int RomanToInt(string s) { int result = 0; Type R = typeof(Roman); string first, second; if (s.Length > 1) { first = s.Substring(0, 1); second = s.Substring(0, 2); } else { first = s.Substring(0, 1); second = ; } foreach (var r in Enum.GetNames(R).Reverse()) { while ((r.Length == 1 && first == r) || (r.Length == 2 && second == r)) { result += int.Parse(Enum.Format(R, Enum.Parse(R, r), d)); int lenR = r.Length, lenS = s.Length; if (lenS - lenR < 1) s = ; else s = s.Substring(lenR, lenS - lenR); if (s.Length > 1) { first = s.Substring(0, 1); second = s.Substring(0, 2); } else if (s.Length == 1) { first = s.Substring(0, 1); second = ; } else { first = ; second = ; } } } return result; }}public enum Roman{ M = 1000, CM = 900, D = 500, CD = 400, C = 100, XC = 90, L = 50, XL = 40, X = 10, IX = 9, V = 5, IV = 4, I = 1};
You can run it ...... However, the efficiency is too low, so you can't bear to look directly ...... So I learned from other gods ......
The following code deeply touched me ...... Array as the index of the array ...... My least common usage ......
class Solution {public: int romanToInt(string s) { unordered_map
map = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; int ret = 0; for (int idx = 0; idx < s.size(); ++idx) { if ((idx < s.size()-1) && (map[s[idx]] < map[s[idx+1]])) { ret -= map[s[idx]]; } else { ret += map[s[idx]]; } } return ret; }};
This algorithm makes full use of the relationship between the order of the two numbers, that is, if I is in front of V, that is, IV, it represents 4, and vice versa, it represents 6. Combined with C ++'s unordered_map, you can use arrays to judge and add or subtract ret.