Nuggets team number online, help you Offer rimmon! Click to see details

I. Topic Description:

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

I 1 V 5 X 10 L 50 C 100 D 500 M 1000 The Roman numeral 2 is written II. Let's write 12 as XII, which is X plus II. 27 write XXVII, XX + V + II. In Roman numerals, the smaller number is usually placed to the right of the larger number. But there are exceptions. For example, instead of writing IIII for 4, I would write IV. The number 1 is to the left of the number 5, which is equal to the large number 5 and the number 4 is obtained by reducing the number 1. Similarly, the number 9 is represented as IX. This special rule only applies in the following six cases: I can be placed to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be placed to the left of D (500) and M (1000) to represent 400 and 900. Given a Roman numeral, convert it to an integer. Make sure the input is in the range 1 to 3999.Copy the code
  • The sample

 

Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90, IV = 4.Copy the code

 

Ii. Thinking analysis:

  • Create a HashMap to map symbols and values, then add a value to the string from left to right if the current character represents a value that is not less than its right hand side;
  • Otherwise, subtract the value. And then you go to the leftmost number, and that’s the answer

Three, AC code

/** * @param {string} s * @return {number} */ var romanToInt = function(s) { const romanObj = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; const res = s.split('').reduce((sum, current, index, arr) => { sum = sum + romanObj[current]; if ((current === 'V' || current === 'X') && arr[index - 1] === 'I') sum -= 2; if ((current === 'L' || current === 'C') && arr[index - 1] === 'X') sum -= 20; if ((current === 'D' || current === 'M') && arr[index - 1] === 'C') sum -= 200; return sum; }, 0); return res; }; Status: Elapsed time: 168 ms Memory consumption: 44.4MBCopy the code

Four,

  • Of course, there is more than one way to do it, and there are many ways to do it, but the idea is similar;
/** * @param {string} s * @return {number} */ var romanToInt = function(s) { let num = 0, obj = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 } let len = s.length for(let i = 0; i < len; i++){ let val = obj[s[i]], after_val = obj[s[i + 1]] if((i ! == len -1) && val < after_val){ num -= val }else{ num += val } } return num };Copy the code
  • There is no convenient way to achieve it

For reference only

Refer to the topic

  • Force button (LeetCode)