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 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是,引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不...

curl和libcurl的区别简介

curl简介 curl是利用URL语法在命令行方式下工作的开源文件传输工具。 它支持很多协议:DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IM...

详解PHP版本兼容之openssl调用参数

背景与问题解决方式 老项目重构支付宝部分代码整合支付宝新的sdk时发现验签总是失败,才发现是open_verify最后的参数传输问题。而open_sign同样如此。本文主要说明open_...

php查询whois信息的方法

本文实例讲述了php查询whois信息的方法。分享给大家供大家参考。具体如下: 这里使用php通过查询whois信息的网站列表进行查询 function whois_query($d...

mod_php、FastCGI、PHP-FPM等PHP运行方式对比

概述 写这篇文章的是因为今天要Ubuntu下搭建LNMP环境,Nginx使用的是PHP-FPM,所以对Web服务器与PHP解释器的交互方式做了个整理。 众所周知,PHP是跨平台、跨服务器...