Day18-13. Roman to Integer

今日题目:13. Roman to Integer(Easy)

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 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.

Example 1:
Input: s = "III"
Output: 3

解题思路

My solution

class Solution:
def romanToInt(self, s: str) -> int:

    romanDict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    sum = 0
    prev = 0
    n = len(s)

    for i in s[::-1]:
        curr = romanDict[i]
        if prev > curr:
            sum -= curr
        else:
            sum += curr
        prev = curr
    
    return sum

Result

https://ithelp.ithome.com.tw/upload/images/20211003/201408433VEYXSAZu8.png


<<:  D3JsDay18 不让资料进坟墓,秒懂农产品分布—实际资料画地图

>>:  Day24 axios基本语法(GET、POST请求)?

Day 18: Security Hub简介

What is Security Hub? Security Hub 是能将所有的资安指标、所有资安...

隐藏&显示画面中间的某区块

缘由: 开发时或多或少会遇到因某个条件地达成,需要显示或隐藏画面中的另一个条件,若是区块在最底部,直...

用 Line LIFF APP 实现信箱验证绑定功能(2) - 使用 Vite 快速打造输入页面

昨天提到,LIFF APP 有可能因为使用者没有绑定 email,或是不授权 email 使用导致无...

铁人赛 Day26 -- 一定要知道的JQuery (二) -- 锚点动画

JQuery-锚点动画 什麽是锚点 & 锚点的作用是什麽 他是超连结的一种,可以帮助我们更快...

React学习动机&前端框架简单介绍

学习动机 过去开发网页前端程序的时候,使用基本的html、css、javascript作为开发的工具...