How PHP realizes the conversion between Arabic and Roman numerals _php skills

Source: Internet
Author: User
Tags php programming

The example in this article describes how PHP realizes the conversion of Arabic and Roman numerals to each other. Share to everyone for your reference. as follows:

<?php//Function that calculates "Roman string to" given Number:function Dec2roman ($f) {//return FALSE if E Ither $f is isn't a real number,//$f are bigger than 3999 or $f is lower or equal to 0:if (!is_numeric ($f) | | $f > 3999 | |
 $f <= 0) return false; Define The Roman figures: $roman = array (' M ' => 1000, ' D ' =>, ' C ' =>, ' L ' =>, ' X ' =
 >, ' 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 False if not at least one-string:if (Is_numeric ($STR)) return false; Define The Roman figures: $roman = array (' M ' => 1000, ' D ' =>, ' C ' =>, ' L ' =>, ' X ' =
 >, ' 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 will help you with your PHP programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.