Problem Statement

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Given a roman numeral, convert it to an integer.

Roman to Integer - LeetCode

Approach

  1. Iterating over the string and keep track of previous value.
  2. If previous value is not less than current value, add the current value to the number.
  3. Else, subtract twice the previous value from the number and add the current value.

Solution in Swift

class Solution {
    func romanToInt(_ s: String) -> Int {
        var number = 0
        var previous = 0

        for char in s {
            let current = switch char {
                case "I": 1
                case "V": 5
                case "X": 10
                case "L": 50
                case "C": 100
                case "D": 500
                case "M": 1000
                default: 0
            }

            if current > previous {
                number -= 2 * previous
            }
            number += current
            previous = current
        }
        return number
    }
}

Complexity

  • Time Complexity: \(O(n)\), where \(n\) is the length of the string.
  • Space Complexity: \(O(1)\)