ninehills / blog

https://ninehills.tech
758 stars 68 forks source link

LeetCode-13. Roman to Integer #20

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

https://leetcode.com/problems/roman-to-integer/#/description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字的定义参见: #19

思路

整数转罗马数用的是各位数字查表,罗马数转数字的时候,也有两种办法

后者显然更简洁

解答


package main

import "fmt"

// ----------------------
func romanToInt(s string) int {
    romanChar := map[byte]int{
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }
    ret := romanChar[s[len(s)-1]]
    for i := len(s) - 2; i >= 0; i-- {
        char := s[i]
        if romanChar[char] < romanChar[s[i+1]] {
            ret = ret - romanChar[char]
        } else {
            ret = ret + romanChar[char]
        }
    }
    return ret
}

// ----------------------

func main() {
    fmt.Println(romanToInt("MMMCMLXXXIX"))
}
ninehills commented 7 years ago

20170722