leetcode.com-problemset-all-013 - Roman to Integer

- 8 mins

题目描述

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol -> Value
I -> 1
V -> 5
X -> 10
L -> 50
C -> 100
D -> 500
M -> 1000
For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

难易程度

Example:

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

PHP实现

方法一

<?php
/**
 * Created by PhpStorm.
 * User: zhanglingyu
 * Date: 2019-04-10
 * Time: 19:17
 */
// 32ms
class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $value = array('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);

        $len = strlen($s);

        $res = 0;
        for ($i=0; $i<$len; $i++){
            $v = $s[$i];

            if ($i != $len-1) {
                $_v = $s[$i+1];
                $av = $v.$_v;
                if (array_key_exists($av, $value)) {
                    $res += $value[$av];
                    $i++;
                    continue;
                }
            }

            $res += $value[$v];

        }

        return $res;
    }
}

class Test extends \PHPUnit\Framework\TestCase
{

    /** @test */
    public function testSolution()
    {
        $solution = new Solution();

        $s = 'MCMXCIV';

        $this->assertEquals($solution->romanToInt($s), 1994);

        $s1 = 'III';

        $this->assertEquals($solution->romanToInt($s1), 3);
    }
}

其他方法

/**
 * @param string $roman
 *
 * @return integer
 */
public function romanToInt(string $roman): int
{
    $map = [
        'I' => 1,
        'V' => 5,
        'X' => 10,
        'L' => 50,
        'C' => 100,
        'D' => 500,
        'M' => 1000,

        // special for diy
        'v' => 4,
        'x' => 9,
        'l' => 40,
        'c' => 90,
        'd' => 400,
        'm' => 900,
    ];

    $special = [
        'IV' => 'v',
        'IX' => 'x',
        'XL' => 'l',
        'XC' => 'c',
        'CD' => 'd',
        'CM' => 'm',
    ];

    foreach ($special as $k => $v) {
        $roman = str_replace($k, $v, $roman);
    }

    $number = 0;
    $roman = str_split($roman);
    foreach ($roman as $item) {
        $number += $map[$item];
    }

    return $number;
}

Go实现

方法一

// 28ms
func romanToInt(s string) int {
    var m map[string]int
	
	m = map[string]int{
		"I": 1,
		"V": 5,
		"X": 10,
		"L": 50,
		"C": 100,
		"D": 500,
		"M": 1000 }
	
	res := 0

	l := len(s)

	for i:=0; i<l; i++  {
		s1 := string(s[i])
		if i < l-1 {
			s2 := string(s[i+1])
			if m[s1] < m[s2] {
				res -= m[s1]
				continue
			}
		}
		
		res += m[s1]
		
	}
	
	return res
}

其他方法

//16ms
var value = map[rune]int{
    'M': 1000,
    'D': 500,
    'C': 100,
    'L': 50,
    'X': 10,
    'V': 5,
    'I': 1,
}

func romanToInt(s string) int {
    var sum int
    var last rune
    for i, r := range s {
        v, l := value[r], value[last]
        sum += v
        last = r
        if i > 0 && v > l {
            sum -= l*2
        }
    }
    return sum
}


//16ms
var order = [7]byte{'M','D','C','L','X','V','I'}
var value = [7]int{1000,500,100,50,10,5,1}

func romanToInt(s string) int {
	if "" == s {return 0}
	return convert([]byte(s))
}

func convert(num []byte) int {
	if nil == num || 0 == len(num) {return 0}
	var idx int
	for i,c := range order {
		idx = bytes.IndexByte(num, c)
		if -1 == idx {continue}
		if idx != 0 {
			return value[i]-convert(num[:idx])+convert(num[idx+1:])
		}
		return value[i]+convert(num[1:])
	}
	return 0
}

PS

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora