如何用代码得到最长的罗马数字字符串

620 阅读1分钟

以下代码返回为1至2099年之间生成的最长的罗马数字字符串。请注意,可以用罗马符号表示的最大数字是3,999(MMMCMXCIX)。



function integerToRoman($year)
{
    /* Ref: https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html 
     *      https://en.wikipedia.org/wiki/Roman_numerals
     */
    
    
    $result = '';

    // Create a lookup array that contains all of the Roman numerals.
    $lookup = array(
                   'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
                   'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
                   'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1
                   );
 
    foreach($lookup as $roman => $value)
    {
        // Determine the number of matches
        $matches = intval($year / $value);

        // Add the same number of characters to the string as the count of $matches
        $result .= str_repeat($roman,$matches);

        // Set the $year to be the remainder of the $year and the value
        $year = $year % $value;
    }
 
    return $result;
}

$longest = '';
$year = '';

for($i=1; $i <= 2099; $i++) {
    $roman = integerToRoman($i);
    if(strlen($roman) > strlen($longest)) {
        $longest = $roman;
        $year = $i;
    }
}

echo $longest . " : " . $year;

//
// MDCCCLXXXVIII : 1888
//

这将是1888年,用罗马数字串'MDCCCLXXXVIII'表示,它有13个字符长。下一个最长的罗马数字是2888,用'MMDCCCLXXXVIII'表示,它有14个字符。