Numbers to Roman Numbers with php

前端 未结 6 1823
[愿得一人]
[愿得一人] 2020-12-24 14:11

I need to transform ordinary numbers to Roman numerals with php and I have this code:

        

        
6条回答
  •  渐次进展
    2020-12-24 14:45

    I found this code here: http://php.net/manual/en/function.base-convert.php

    Optimized and prettified function:

    /**
     * @param int $number
     * @return string
     */
    function numberToRomanRepresentation($number) {
        $map = 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);
        $returnValue = '';
        while ($number > 0) {
            foreach ($map as $roman => $int) {
                if($number >= $int) {
                    $number -= $int;
                    $returnValue .= $roman;
                    break;
                }
            }
        }
        return $returnValue;
    }
    

提交回复
热议问题