Roman Numeral to integer function

basically i am trying to create a function that will turn a Roman numeral into a integer.

I have an array:

$roman_numerals=[
    'M'  => 1000,
    'CM' => 900,
    'D'  => 500,
    'CD' => 400,
    'C'  => 100,
    'XC' => 90,
    'L'  => 50,
    'XL' => 40,
    'X'  => 10,
    'IX' => 9,
    'V'  => 5,
    'IV' => 4,
    'I'  => 1
];

I'm fairly new to PHP so i'm still getting used to the way of think so please bear in mind i'm still learning :)

here is my function - or what i have so far:

//Array
function romanToInteger($key)
{
$roman_numerals=[
    'M'  => 1000,
    'CM' => 900,
    'D'  => 500,
    'CD' => 400,
    'C'  => 100,
    'XC' => 90,
    'L'  => 50,
    'XL' => 40,
    'X'  => 10,
    'IX' => 9,
    'V'  => 5,
    'IV' => 4,
    'I'  => 1
];

$roman = intval($key);
$result = 0;

foreach ($roman_numerals as $key => $value) {
    while (strpos($roman, $key) === 0) {
        $result += $value;
        $roman = substr($roman, strlen($key));
    }
}
var_dump($roman); //test
echo $result;
}

i have been at this for hours and would just like the see the light of it, any advice would be greatly appreciated.

when i run it in the command line with

echo romanToInteger('I');

i just get returned 0 and i think its something to do with my intval?

Sorry again for being a noob, help appreciated though or any pointers! :)


Yes it has something to do with the intval .

You're basically casting your roman input into an integer rendering it into 0 .

Remove that:

function romanToInteger($key)
{
    $romans = [
        'M' => 1000,
        'CM' => 900,
        'D' => 500,
        'CD' => 400,
        'C' => 100,
        'XC' => 90,
        'L' => 50,
        'XL' => 40,
        'X' => 10,
        'IX' => 9,
        'V' => 5,
        'IV' => 4,
        'I' => 1,
    ];

    $roman = $key;
    $result = 0;

    foreach ($romans as $key => $value) {
        while (strpos($roman, $key) === 0) {
            $result += $value;
            $roman = substr($roman, strlen($key));
        }
    }
    echo $result;
}

romanToInteger('IV');

Sample Output

链接地址: http://www.djcxy.com/p/85186.html

上一篇: 从LibGit2Sharp中的提交中获取修改/添加/删除的文件

下一篇: 罗马数字到整数函数