CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Roman to Integer
string
math
hashtable
# Roman to Integer ## Difficulty Easy ## Tags `string`, `math`, `hash table` ## Problem Statement Given a Roman numeral string, convert it to an integer. Roman numerals use these symbols: - I = 1 - V = 5 - X = 10 - L = 50 - C = 100 - D = 500 - M = 1000 When a smaller value precedes a larger value, it represents subtraction (e.g., IV = 4, IX = 9). ## Constraints - 1 ≤ s.length ≤ 15 - `s` contains only characters: I, V, X, L, C, D, M - Input is guaranteed to be a valid Roman numeral in range [1, 3999] ## Signatures ### Python ```python def roman_to_int(s: str) -> int: pass ``` ### Java ```java public class Solution { public int roman_to_int(String s) { return null; } } ``` ### Csharp ```csharp public class Solution { public int roman_to_int(string s) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: int roman_to_int(string s) { } }; ``` ### C ```c int roman_to_int(char* s) { } ``` ### Ruby ```ruby def roman_to_int(s) end ``` ### Perl ```perl sub roman_to_int { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def roman_to_int(s: String): Int = { } } ``` ### Haskell ```haskell roman_to_int :: ... -> ... roman_to_int args = undefined ``` ### Clojure ```clojure (defn roman_to_int [s] ) ``` ### Scheme ```scheme (define (roman_to_int s) ) ``` ## Examples ### Example 1 **Input:** ``` s = "III" ``` **Output:** ``` 3 ``` **Explanation:** III = 1 + 1 + 1 = 3 ### Example 2 **Input:** ``` s = "LVIII" ``` **Output:** ``` 58 ``` **Explanation:** L = 50, V = 5, III = 3. Total = 58. ### Example 3 **Input:** ``` s = "MCMXCIV" ``` **Output:** ``` 1994 ``` **Explanation:** M=1000, CM=900, XC=90, IV=4. Total = 1994. ### Example 4 **Input:** ``` s = "IV" ``` **Output:** ``` 4 ``` **Explanation:** I before V means subtraction: 5 - 1 = 4. ## Hints 1. Create a mapping of Roman characters to values. 2. Iterate through the string from left to right. 3. If current value < next value, subtract current from total. 4. Otherwise, add current to total.
Login required
Please log in to view the solution editor and submit code.
Login
Register