美文网首页
Roman to Integer go语言实现

Roman to Integer go语言实现

作者: fjxCode | 来源:发表于2018-09-22 15:35 被阅读0次

Roman to Integer

题目描述

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

思路:

  • 题意:罗马数字最多只有一个“左边修饰”
  • 有左边修饰进两位,默认进一位,计算值,并累加。

解:

package main

import "fmt"

func romanToInt(s string) int {
    units := make(map[rune]int, 7)
    units['I'] = 1
    units['V'] = 5
    units['X'] = 10
    units['L'] = 50
    units['C'] = 100
    units['D'] = 500
    units['M'] = 1000
    res := 0
    sSlice := []rune(s)
    i :=0
    for ; i < len(sSlice)-1;  {
        if units[sSlice[i]] < units[sSlice[i+1]] {
            res += units[sSlice[i+1]] - units[sSlice[i]]
            i = i+2
        }else {
            res += units[sSlice[i]]
            i++
        }
    }
    if i != len(sSlice){
        res += units[sSlice[i]]
    }

    return res
}

func main()  {
    s := "III"
    res := romanToInt(s)
    fmt.Print(res)
}

相关文章

网友评论

      本文标题:Roman to Integer go语言实现

      本文链接:https://www.haomeiwen.com/subject/xqkxoftx.html