• Coding
  • Exercise - Decimal to Roman conversion

Write a program that converts decimals into roman numerals. Limit yourself to numbers between 1 and 89.


1  => I
85 => LXXXV
45 => XLV
If you have trouble understanding the above conversions, I strongly suggest you take a look at this page.
In what language do you need it?
The one you prefer. I tend to write in C.
That's a nice exercise, here's my solution in php (from 1 to 999):
<?php
$decimal='222';
$romans=array('I','V','X','L','C','D','M');
$digits=array_reverse(str_split($decimal));
$x=0;
$final="";
foreach($digits as $d){
	if($d==4){
		$v=$romans[$x].$romans[$x+1];
	}
	else if($d==9){
		$v=$romans[$x].$romans[$x+2];
	}
	else{
	$n=str_pad("", $d , $romans[$x]);
	$n5=str_pad("", 5 , $romans[$x]);
	$v=str_replace($n5,$romans[$x+1],$n);
	}
	$x+=2;
	$final=$v.$final;
}
echo $final;
?>
Here's a demo