• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Easy: 13. Roman to Integer

一、题目

Given a roman numeral, convert it to an integer.

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

二、思路解析

罗马数规则如下:

将数字和字符串对应,当然需要用到字典,循环遍历给定的字符串中的字符,如果当前字符所对应的字典值比下一个字符所对应的字典值大,那么就执行加的操作,反之则减。这里有个小trick,由于鄙人python并不精通,不知道怎么同时访问字符串中的当前字符和当前字符的下一个字符,所以可以借用变量sums,初始化为0,然后按上述规则累加累减,最后再加上最后一个字符的字典值即可。

三、代码

#coding:utf-8

def romanToInt(s):
    """
    :type s: str
    :rtype: int
    """
    charToInt = {"I": 1,
                 "V": 5,
                 "X": 10,
                 "L": 50,
                 "C": 100,
                 "D": 500,
                 "M": 1000}

    sums = 0
    for item in range(len(s)-1):
        if charToInt[s[item]]>=charToInt[s[item+1]]:
            sums += charToInt[s[item]]
        else:
            sums = sums - charToInt[s[item]]
    print(sums+charToInt[s[-1]])
    return sums+charToInt[s[-1]]

if __name__ == '__main__':
    romanToInt("DCXIX")

  

 

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-18 11:16  乐晓东随笔  阅读(117)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3