Roman to Integer | Leetcode | Golang Solution with Explaination

Roman to Integer | Leetcode | Golang Solution with Explaination

Sunday, February 25, 2024
~ 48 min read
In this tutorial, learn how to efficiently convert Roman numerals to integers using a Go solution for the Roman to Integer problem on LeetCode. Gain insights into the algorithm and its implementation in Golang, along with a step-by-step explanation of the solution's logic.

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

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example,Ā 2Ā is written asĀ IIĀ in Roman numeral, just two ones added together.Ā 12Ā is written asĀ XII, which is simplyĀ X + II. The numberĀ 27Ā is written asĀ XXVII, which isĀ XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is notĀ IIII. Instead, the number four is written asĀ IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asĀ IX. There are six instances where subtraction is used:

  • IĀ can be placed beforeĀ VĀ (5) andĀ XĀ (10) to make 4 and 9.Ā 
  • XĀ can be placed beforeĀ LĀ (50) andĀ CĀ (100) to make 40 and 90.Ā 
  • CĀ can be placed beforeĀ DĀ (500) andĀ MĀ (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.


Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Ā 

Constraints:

  • 1 <= s.length <= 15
  • sĀ contains onlyĀ the charactersĀ ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It isĀ guaranteedĀ thatĀ sĀ is a valid roman numeral in the rangeĀ [1, 3999].


Solution:

func romanToInt(s string) int {
    // Define a map to store the numeric values of each Roman symbol
    symbols_map := map[string]int{
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000,
    }
    
    // Initialize the result value
    v := 0
    // Store the previous symbol to handle subtraction cases
    prev := ""
    
    // Loop through each character in the input string
    for _, c := range s {
        // Check if the current symbol's value is greater than the previous one
        if symbols_map[string(c)] > symbols_map[prev] {
            // If so, subtract the previous symbol's value from the result
            v = v - symbols_map[prev]
            // Add the difference between the current symbol's value and the previous one to the result
            v = v + (symbols_map[string(c)] - symbols_map[prev])
        } else {
            // If not, simply add the current symbol's value to the result
            v += symbols_map[string(c)]
        }
        // Update the previous symbol for the next iteration
        prev = string(c)
    }
    
    // Return the final integer value
    return v
}


Explaination:

  1. Symbol Mapping: The function starts by defining a mapping between Roman symbols and their corresponding integer values using a Go map.
  2. Initialization: It initializes the result variable v to 0 and a variable prev to store the previous symbol encountered during iteration.
  3. Iteration: The function iterates through each character in the input string s.
  4. Comparing Symbols: For each symbol, it compares its numeric value with the previous one. If the current symbol's value is greater than that of the previous symbol, it implies a subtraction case (e.g., IV = 5 - 1 = 4).
  5. Updating Result: Accordingly, it updates the result variable v by subtracting the value of the previous symbol and then adding the difference between the current symbol's value and the previous one. If no subtraction is needed, it simply adds the current symbol's value to the result.
  6. Updating Previous Symbol: Finally, it updates the prev variable to store the current symbol for the next iteration.
  7. Result: Once all symbols are processed, it returns the final integer value representing the input Roman numeral string.


Thanks for reading this ā¤.

Post a comment

Comments

Join the conversation and share your thoughts! Leave the first comment.

Get your FREE PDF on "100 Ways to Try ChatGPT Today"

Generating link, please wait for: 60 seconds

Search blogs

No blog posts found