Fork me on GitHub
打赏

LeetCode-13. Roman to Integer | 罗马数字转整数

题目

LeetCode
力扣

题解

先维护一个map,用于建立罗马数字和整数的关系,接着挨个破译即可。

//Go
func romanToInt(s string) int {
    var charToIntMap = make(map[byte]int, 8)
    charToIntMap['I'] = 1
    charToIntMap['V'] = 5
    charToIntMap['X'] = 10
    charToIntMap['L'] = 50
    charToIntMap['C'] = 100
    charToIntMap['D'] = 500
    charToIntMap['M'] = 1000
    sum := 0
    for i:= 0; i < len(s); i++ {
        switch s[i] {
            case 'I':
            if i + 1 < len(s) && (s[i+1] == 'V' || s[i+1] == 'X') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            case 'X':
            if i + 1 < len(s) && (s[i+1] == 'L' || s[i+1] == 'C') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            case 'C':
            if i + 1 < len(s) && (s[i+1] == 'D' || s[i+1] == 'M') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            default:
            sum += charToIntMap[s[i]]
        }
    }

    return sum
}

执行结果:

leetcode-cn执行:
执行用时:16 ms, 在所有 Go 提交中击败了22.55%的用户
内存消耗:3.1 MB, 在所有 Go 提交中击败了78.12%的用户

leetcode执行:
Runtime: 8 ms, faster than 64.36% of Go online submissions for Roman to Integer.
Memory Usage: 3.1 MB, less than 100.00% of Go online submissions for Roman to Integer.

github博客地址

posted @ 2021-02-06 21:45  Zoctopus_Zhang  阅读(40)  评论(0编辑  收藏  举报
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);