13. Roman to Integer (Easy)

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

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

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, w hich is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the nu meral 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:

Roman Value Explanation
III 3
IV 4
IX 10
LVIII 58 L = 50, V= 5, III = 3
"MCMXCIV" 1994 M = 1000, CM = 900, XC = 90 and IV = 4

OCaml Solution

 
let explode s = List.init (String.length s) (String.get s)
;;

let get x =                                                                                
  match x with                                                                             
  |'I' -> 1                                                                                
  |'V' -> 5                                                                                       
  |'X' -> 10
  |'L' -> 50                                                                                           
  |'C' -> 100
  |'D' -> 500
  |'M' -> 1000                                                                             
;; 

let r2n roman =                                                                            
  let lst = (explode roman) in                                                             
  let rec aux r =                                                                          
    match r with                                                                           
      []->0                                                                                
     |[x]-> get x                                                                          
     |h1::h2::t ->                                                                         
       if get h1 >= get h2 then get h1 + aux (h2::t)                                       
       else get h2 - get h1 + aux t                                                        
  in aux lst                                                                               
  ;;