Hola,
Pues nada, que no he podido evitarlo:
Código Delphi
[-]
unit URomanNumbers;
interface
uses
SysUtils;
type
TRomanNumbers = class(TObject)
public
class function Validate(roman: string) : boolean;
class function IntToRoman(value: integer) : string;
class function RomanToInt(const roman: string) : integer;
end;
implementation
resourcestring
rsErrorEntradaInvalida1 = 'No es posible convertir un número romano menor que cero.';
rsErrorEntradaInvalida2 = 'No es posible convertir un número romano mayor que 3999.';
rsErrorEntradaInvalida3 = 'El número romano entregado parece no ser del todo bueno.';
class function TRomanNumbers.IntToRoman(value: integer): string;
begin
result := '';
if(value = 0) then Exit;
if(value < 0) then raise
Exception.Create(rsErrorEntradaInvalida1);
if (value <= 3999) then
begin
while(value / 1000 >= 1) do
begin
result := result + 'M';
value := value - 1000;
end;
if (value / 900 >= 1) then
begin
result := result + 'CM';
value := value - 900;
end;
if (value / 500 >= 1) then
begin
result := result + 'D';
value := value - 500;
end;
if (value / 400 >= 1) then
begin
result := result + 'CD';
value := value - 400;
end;
while(value / 100 >= 1) do
begin
result := result + 'C';
value := value - 100;
end;
if (value / 90 >= 1) then
begin
result := result + 'XC';
value := value - 90;
end;
if (value / 50 >= 1) then
begin
result := result + 'L';
value := value - 50;
end;
if (value / 40 >= 1) then
begin
result := result + 'XL';
value := value - 40;
end;
while(value / 10 >= 1) do
begin
result := result + 'X';
value := value - 10;
end;
if (value / 9 >= 1) then
begin
result := result + 'IX';
value := value - 9;
end;
if (value / 5 >= 1) then
begin
result := result + 'V';
value := value - 5;
end;
if (value / 4 >= 1) then
begin
result := result + 'IV';
value := value - 4;
end;
while(value >= 1 ) do
begin
result := result + 'I';
value := value - 1;
end;
end
else
raise Exception.Create(rsErrorEntradaInvalida2);
end;
class function TRomanNumbers.RomanToInt(const roman: string) : integer;
var
i: integer;
lastChar: Char;
begin
result := 0;
if Validate(roman) then
begin
lastChar := ' ';
for i := Length(roman) downto 1 do
begin
case roman[i] of
'I': if (lastChar = 'X') or (lastChar = 'V') then
Dec(result) else Inc(result);
'V': Inc(result, 5);
'X': if (lastChar = 'C') or (lastChar = 'L') then
Dec(result, 10) else Inc(result, 10);
'L': Inc(result, 50);
'C': if (lastChar = 'M') or (lastChar = 'D') then
Dec(result, 100) else Inc(result, 100);
'D': Inc(result, 500);
'M': Inc(result, 1000);
end;
lastChar := roman[i];
end;
end
else
raise Exception.Create(rsErrorEntradaInvalida3);
end;
class function TRomanNumbers.Validate(roman: string) : boolean;
var
i: integer;
begin
result := false;
for i := 1 to Length(roman) do
result := (roman[i] = 'I')
or (roman[i] = 'V')
or (roman[i] = 'X')
or (roman[i] = 'L')
or (roman[i] = 'C')
or (roman[i] = 'D')
or (roman[i] = 'M');
end;
end.