CynicRus
2012-12-25 02:14:24
Converts the integer to the Roman numerals.
ie: 1245 > MCCXLV:)
OldSchool style:
Without GoTo:
ie: 1245 > MCCXLV:)
OldSchool style:
function IntToRoman(Value: Longint): string;
Label
A500, A400, A100, A90, A50, A40, A10, A9, A5, A4, A1;
begin
Result := '';
while Value >= 1000 do begin
DecEx(Value, 1000); Result := Result + 'M';
end;
if Value < 900 then goto A500
else begin
DecEx(Value, 900); Result := Result + 'CM';
end;
goto A90;
A400:
if Value < 400 then goto A100
else begin
DecEx(Value, 400); Result := Result + 'CD';
end;
goto A90;
A500:
if Value < 500 then goto A400
else begin
DecEx(Value, 500); Result := Result + 'D';
end;
A100:
while Value >= 100 do begin
DecEx(Value, 100); Result := Result + 'C';
end;
A90:
if Value < 90 then goto A50
else begin
DecEx(Value, 90); Result := Result + 'XC';
end;
goto A9;
A40:
if Value < 40 then goto A10
else begin
DecEx(Value, 40); Result := Result + 'XL';
end;
goto A9;
A50:
if Value < 50 then goto A40
else begin
DecEx(Value, 50); Result := Result + 'L';
end;
A10:
while Value >= 10 do begin
DecEx(Value, 10); Result := Result + 'X';
end;
A9:
if Value < 9 then goto A5
else begin
Result := Result + 'IX';
end;
Exit;
A4:
if Value < 4 then goto A1
else begin
Result := Result + 'IV';
end;
Exit;
A5:
if Value < 5 then goto A4
else begin
DecEx(Value, 5); Result := Result + 'V';
end;
goto A1;
A1:
while Value >= 1 do begin
Dec(Value); Result := Result + 'I';
end;
end;
Without GoTo:
function IntToRoman(Value: LongInt): String;
var
j: Integer;
Arabics: TIntegerArray;
Romans: TStringArray;
begin
Arabics:=[1, 4,5,9,10,40,50,90,100,400,500,900,1000];
Romans:=['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M'];
for j := 12 downto 0 do
while (Value >= Arabics[j]) do begin
Value := Value - Arabics[j];
Result := Result + Romans[j];
end;
end;
function RomanToInt(const Value: string): integer;
var
i, lastValue, curValue: integer;
begin
Result := 0;
lastValue := 0;
for i := Length(Value) downto 1 do
begin
case UpperCase(Value[i]) of
'C':
curValue := 100;
'D':
curValue := 500;
'I':
curValue := 1;
'L':
curValue := 50;
'M':
curValue := 1000;
'V':
curValue := 5;
'X':
curValue := 10;
else
begin
WriteLn('Invalid character: '+ toStr(Value[i]));
Exit;
end
end;
if curValue < lastValue then
DecEx(Result, curValue)
else
IncEx(Result, curValue);
lastValue := curValue;
end;
end;