php实现阿拉伯数字和罗马数字相互转换的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php实现阿拉伯数字和罗马数字相互转换的方法。分享给大家供大家参考。具体如下:

<?php
// Function that calculates the roman string to the given number:
function dec2roman($f)
{
 // Return false if either $f is not a real number, 
 //$f is 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' => 500,
  'C' => 100,
  'L' => 50,
  'X' => 10,
  '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 letter is in the string:
  if(is_numeric($str)) return false;
 // Define the roman figures:
  $roman = array(
  'M' => 1000,
  'D' => 500,
  'C' => 100,
  'L' => 50,
  'X' => 10,
  '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);  
?>

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP访问数据库集群的方法小结

本文总结分析了PHP访问数据库集群的方法。分享给大家供大家参考,具体如下: 一般常见的有三种做法: 1、自动判断sql是否为读,来选择数据库的连接: 实例化php DB类的时候,需要一次...

php如何实现不借助IDE快速定位行数或者方法定义的文件和位置

php 如何实现不借助IDE快速定位行数或者方法定义的文件和位置 借助了ReflectionMethod的一些特性,可以快速获得函数或者方法是在哪个文件的什么位置定义的,对于调试没有文档...

C# Assembly类访问程序集信息

C#中通过Assembly类可以访问程序集信息. 1.允许访问给定程序集的元元素,包含可以加载和执行程序集的方法; 2.加载程序集:使用静态方法Assembly.Load(程序集名称)或...

php实现utf-8和GB2312编码相互转换函数代码

复制代码 代码如下:<?php /********************************************  *  * 函数名:get...

SAE实时日志接口SDK用法示例

本文实例讲述了SAE实时日志接口SDK用法。分享给大家供大家参考,具体如下: 新浪SAE是新浪研发中心开发的国内首个公有云平台,从2009年开始到现在也是也来越成熟,开放了很多接口以及服...