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

yipeiwu_com6年前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冒泡算法详解(递归实现)

实现 复制代码 代码如下: /*     冒泡算法(递归实现) */ function maoPao($array, $index=0) {  &...

PHP经典设计模式之依赖注入定义与用法详解

本文实例讲述了PHP经典设计模式之依赖注入定义与用法。分享给大家供大家参考,具体如下: 依赖注入的实质就是把一个类不可能更换的部分和可更换的部分分离开来,通过注入的方式来使用,从而达到解...

PHP实现提取多维数组指定一列的方法总结

本文实例讲述了PHP实现提取多维数组指定一列的方法。分享给大家供大家参考,具体如下: PHP中对多维数组特定列的提取,是个很常用的功能,正因为如此,PHP在5.5.0版本之后,添加了一个...

php模块memcache和memcached区别分析

1.目前大多数php环境里使用的都是不带d的memcache版本,这个版本出的比较早,是一个原生版本,完全在php框架内开发的。与之对应的带d的memcached是建立在libmemca...

使用PHP json_decode可能遇到的坑与解决方法

前言 最近在做网站 的时候用到了json_decode函数,发现了一个问题,现在总结分享出来供大家参考学习,话不多说了,来一起看看详细的介绍吧。 场景: 某项目客户反馈,输出的结果 JS...