LeetCode Solution, Easy, 13. Roman to Integer

羅馬符號轉數值

The link is below and you could see the description. I will use several languages to solve this problem and explain how to solve the problem. Loading... Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared…leetcode.com

JavaScript

/**
 * [@param](http://twitter.com/param) {string} s
 * [@return](http://twitter.com/return) {number}
 */
var romanToInt = function(s) {
  const romanNumerals = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000
  };

  if (s.length < 1) return null;

  let result = romanNumerals[s[s.length - 1]];
  for (let i = 0; i < s.length - 1; i++) {
    if (romanNumerals[s[i]] < romanNumerals[s[i + 1]]) {
      result -= romanNumerals[s[i]];
    } else {
      result += romanNumerals[s[i]];
    }
  }

  return result;
};

Step 1:先建立一個 object 儲存羅馬數字的對照表

Step 2:判斷如果是只有一位數的則直接回傳 null

Step 3:先將字串的最後一位的羅馬數字對照 romanNumerals,得出數字後儲存到 result。使用迴圈遍歷字串 s ,如果遍歷的值小於下一位的值,則 result 相減,反之相加。最後回傳 result

Python3

class Solution:
    def romanToInt(self, s: str) -> int:
        """
        :type s: str
        :rtype: int
        """
        roman = {
            'M': 1000,
            'D': 500,
            'C': 100,
            'L': 50,
            'X': 10,
            'V': 5,
            'I': 1
        }

        total = roman[s[-1]]
        for i in range(len(s) - 1):
            if roman[s[i]] < roman[s[i + 1]]:
                total -= roman[s[i]]
            else:
                total += roman[s[i]]
        return total

Go

func romanToInt(s string) int {

  mapping := map[string]int{
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000,
  }

  var max int = 0
  var sum int = 0

  for i := len(s) - 1; i >= 0; i-- {
    romanLetter := s[i : i+1]
    romanValue := mapping[romanLetter]

    if romanValue < max {
      sum -= romanValue
    } else {
      max = romanValue
      sum += romanValue
    }
  }

  return sum
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!