Logo de kxs.frCours d'informatique pour le lycée et la prépa

Exercices

1) Écrire une fonction récursive bin qui convertit un entier positif sous forme de chaine de caractère en binaire.

# let rec bin n =
if n / 2 = 0 then string_of_int (n mod 2)
else bin (n / 2) ^ string_of_int (n mod 2);;

2) Écrire une fonction recursive dec qui convertit un nombre binaire sous forme de chaine de caractère en entier.

# let rec dec s =
if String.length s = 0 then 0
else int_of_string (String.sub s 0 1) * int_of_float(2.0 ** float_of_int (String.length s - 1)) + dec (String.sub s 1 (String.length s - 1));;
# let rec frombin s =
if String.length s = 0 then 0
else int_of_string (String.make 1 s.[String.length s - 1]) + 2 * frombin (String.sub s 0 (String.length s - 1));;

3) Écrire une fonction récursive roman qui convertit un nombre entier en une chaîne représentant le nombre en chiffres romains. (on rapellera que 1000 -> M, 500 -> D, 100 -> C, 50 -> L, 10 -> X, 5 -> V et 1 -> I)

# let rec roman x =
if x = 0 then ""
else if x >= 1000 then "M" ^ roman (x - 1000)
else if x >= 900 then "CM" ^ roman (x - 900)
else if x >= 500 then "D" ^ roman (x - 500)
else if x >= 400 then "CD" ^ roman (x - 400)
else if x >= 100 then "C" ^ roman (x - 100)
else if x >= 90 then "XC" ^ roman (x - 90)
else if x >= 50 then "L" ^ roman (x - 50)
else if x >= 40 then "XL" ^ roman (x - 40)
else if x >= 10 then "X" ^ roman (x - 10)
else if x >= 9 then "IX" ^ roman (x - 9)
else if x >= 5 then "V" ^ roman (x - 5)
else if x >= 4 then "IV" ^ roman (x - 4)
else "I" ^ roman (x - 1);;

4) Écrire une fonction récursive from_roman qui convertit une chaîne représentant un nombre en chiffres romains en un nombre entier.

# let rec from_roman s prec =
if String.length s = 0 then 0
else
	let c =  s.[String.length s - 1] in
	let n =
		if c = 'I' then 1 
		else if c = 'V' then 5
		else if c = 'X' then 10
		else if c = 'L' then 50
		else if c = 'C' then 100
		else if c = 'D' then 500
		else 1000
	in (if n >= prec then n else -n) + from_roman (String.sub s 0 (String.length s - 1)) n;;