罗马数字转整形

class Solution
{
    public array $rules = [
        'I' => 1,
        'V' => 5,
        'X' => 10,
        'L' => 50,
        'C' => 100,
        'D' => 500,
        'M' => 1000,
    ];

    /**
     * @param  String  $s
     * @return Integer
     */
    function romanToInt(string $s): int
    {
        $sum = 0;

        $items = str_split($s);

        foreach ($items as $key => &$item) {
            if (isset($items[$key + 1])) {
                $nextItem = $items[$key + 1];
            }

            if (isset($nextItem)) {
                if ($item === 'I' && in_array($nextItem, ['V', 'X'])) {
                    $sum += $this->rules[$nextItem] - 1;
                    unset($items[$key + 1]);
                } elseif ($item === 'X' && in_array($nextItem, ['L', 'C'])) {
                    $sum += $this->rules[$nextItem] - 10;
                    unset($items[$key + 1]);
                } elseif ($item === 'C' && in_array($nextItem, ['D', 'M'])) {
                    $sum += $this->rules[$nextItem] - 100;
                    unset($items[$key + 1]);
                } else {
                    $sum += $this->rules[$item];
                }
            } else {
                $sum += $this->rules[$item];
            }
        }

        return $sum;
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
无论在现实或是网络中,我都是孤独的。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!