php實現(xiàn)阿拉伯數(shù)字和羅馬數(shù)字相互轉(zhuǎn)換的方法
更新時間:2015年04月17日 11:31:06 作者:皮蛋
這篇文章主要介紹了php實現(xiàn)阿拉伯數(shù)字和羅馬數(shù)字相互轉(zhuǎn)換的方法,涉及php字符串操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php實現(xiàn)阿拉伯數(shù)字和羅馬數(shù)字相互轉(zhuǎn)換的方法。分享給大家供大家參考。具體如下:
<?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操作mysql執(zhí)行數(shù)據(jù)庫查詢的一些常用操作匯總
本篇文章是對關于php操作mysql執(zhí)行數(shù)據(jù)庫查詢的一些常用操作進行了詳細的匯總介紹,需要的朋友參考下2013-06-06
PHP函數(shù)preg_match_all正則表達式的基本使用詳細解析
以下是對PHP中的函數(shù)preg_match_all正則表達式的基本使用進行了詳細的分析介紹,需要的朋友可以過來參考下2013-08-08
php數(shù)組函數(shù)序列之next() - 移動數(shù)組內(nèi)部指針到下一個元素的位置,并返回該元素值
next() 函數(shù)把指向當前元素的指針移動到下一個元素的位置,并返回該元素的值。如果內(nèi)部指針已經(jīng)超過數(shù)組的最后一個元素,函數(shù)返回 false2011-10-10
在MongoDB中模擬Auto Increment的php代碼
MySQL用戶多半都有Auto Increment情結,不過MongoDB缺省并沒有實現(xiàn),所以需要模擬一下,編程語言以PHP為例2011-03-03

