PHP implements the method of converting Arabic numerals and Roman numerals to each other, Arabic roman numerals
In this paper, we describe how PHP implements the conversion of Arabic numerals and Roman numerals. Share to everyone for your reference. Specific as follows:
<?php//Function that calculates the Roman string to the given number:function Dec2roman ($f) {//Return false if either $f is isn't a real number,//$f is bigger than 3999 or $f are lower or equal to 0:if (!is_numeric ($f) | | $f > 3999 | | $f <= 0) return false; Define The Roman figures: $roman = array (' M ' = = +, ' D ' = +, ' C ' = +, ' L ' = +, ' X ' = 1 0, ' V ' = 5, ' I ' + 1); Calculate the needed Roman Figures:foreach ($roman as $k + $v) if (($amount [$k] = Floor ($f/$v)) > 0) $f-= $ amount[$k] * $V; Build the string: $return = '; foreach ($amount as $k = = $v) {$return. = $v <= 3? str_repeat ($k, $v): $k. $old _k; $old _k = $k; }//Replace Some spacial cases and return the String:return str_replace (Array (' VIV ', ' LXL ', ' DCD '), Array (' IX ', ' XC ', ' CM '), $return);} Echo Dec2romen (1981);//Function to get the decimal value of a Roman string:function Roman2dec ($str = ") {//Return FA LSE if not at least one letter is in the String:if (Is_numeric ($STR)) return false; Define The Roman figures: $roman = array (' M ' = = +, ' D ' = +, ' C ' = +, ' L ' = +, ' X ' = 1 0, ' V ' = 5, ' I ' + 1); Convert the string to an array of Roman values:for ($i = 0; $i < strlen ($STR); $i + +) if (Isset ($roman [Strtoupper ($ str[$i])) $values [] = $roman [Strtoupper ($str [$i])]; Calculate the sum of that array: $sum = 0; while ($current = current ($values)) {$next = next ($values); $next > $current? $sum + = $next-$current + 0 * Next ($values): $sum + = $current; }//Return the Value:return $sum;} echo Roman2dec (IX); ?>
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/985266.html www.bkjia.com true http://www.bkjia.com/PHPjc/985266.html techarticle PHP to achieve the conversion of Arabic numerals and Roman numerals, Arabic and Roman numerals in this paper, we describe the way in which PHP implements the conversion of Arabic numerals and Roman numerals to each other. Share to everyone ...