Overview

Roman Numerals

Demonstrates string building and array-based lookup tables. This example showcases the 'weights' and 'symbols' constant arrays, 'High' property for array bounds, and efficient string concatenation using the '+=' operator.

Source Code

const weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
function ToRoman(n : Integer) : String;
var i, w : Integer;
begin
   if n <= 0 then Exit('N/A');
   for i := 0 to weights.High do begin
      w := weights[i];
      while n >= w do begin
         Result += symbols[i];
         n -= w;
      end;
      if n = 0 then Break;
   end;
end;
PrintLn('2024 -> ' + ToRoman(2024));

Result

2024 -> MMXXIV
On this page