013_RomanToInteger


#####solution1####faster####
def romanToInt(s):
d={
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
i = 1
count = last = d[s[0]]
while i < len(s):
current = d[s[i]]
if current > last:
count -= last * 2
count += current
last = current
i += 1
return count
# ########solution2########
# def romanToInt(s):
# d = {'I': 1,
# 'V': 5,
# 'X': 10,
# 'L': 50,
# 'C': 100,
# 'D': 500,
# 'M': 1000
# }
# res = 0
# if len(s) < 2:
# return d[s[0]]
# res = res + d[s[0]]
# for i in range(1,len(s)):
# res = res + d[s[i]]
# if d[s[i]] > d[s[i - 1]]:
# res = res - 2 * d[s[i-1]]
# return res
#
#
# if __name__=='__main__':
# m="MCMXCIV"
# print(romanToInt(m))
分析:
current记录当前元素值,last记录前一个元素值,count记录current之前所有元素的和,也就是加上了last。
当current大于last时,count需要先减去last再加上current-last,即count-2*last+current
当current小于last时,count直接加上当前current即可,即count+current
013_RomanToInteger的更多相关文章
随机推荐
- velocity模板引擎 -- java.io.FileNotFoundException: velocity.log (Permission denied)
问题原因是velocity的日志框架导致(velocity是使用自己封装的日志框架记录日志的),velocity在初始化Logger时,如果没有读取到配置文件,则会使用默认的velocity.log做 ...
- HTML5 canvas clearRect() 方法
浏览器支持 Internet Explorer 9.Firefox.Opera.Chrome 以及 Safari 支持 clearRect() 方法. 注释:Internet Explorer 8 或 ...
- Java 8 新特性:6-Optional类
(原) 先看看上面的说明: /** * A container object which may or may not contain a non-null value. * If a value i ...
- Vultr CentOS 7 安装 Docker
前言 最近在梳理公司的架构,想用 VPS 先做一些测试,然后就开始踩坑了!我用 Vultr 新买了个 VPS. 安装的 CentOS 版本: [root@dbn-seattle ~]# cat /et ...
- Linux内存管理 (15)页面迁移
专题:Linux内存管理专题 关键词:RMAP.页面迁移. 相关章节:反向映射RMAP.内存规整. 页面迁移的初衷是为NUMA系统提供一种将进程迁移到任意内存节点的能力,后来内存规整和内存热插拔场景都 ...
- ELement-UI之树形表格(treeTable&&treeGrid)
先上图来一波 支持无限层级,支持新增子级时自动打开父级,支持编辑时自动打开父级,执行操作时自带动画效果,支持初始化时设置全部打开或者关闭,支持一键展开与关闭丝滑般的无延迟 由于基于el-table扩展 ...
- 初次使用Mybatis
目录 mybatis简介 导入jar包 创建数据库以及数据库表 创建实体类 创建mapper.xml文件 配置mybatis 测试mybatis 三种查询方式 selectOne selectList ...
- Babel插件开发入门指南
文章概览 主要包括:Babel如何进行转码.插件编写的入门基础.实例讲解如何编写插件. 阅读本文前,需要读者对Babel插件如何使用.配置有一定了解,可以参考笔者之前的文章. 本文所有例子可以在 笔者 ...
- Maven 建立的项目resource对应的实际位置
如图,springmvc-servlet.xml在项目中实际位置为: WEB-INF/classes/config/springmvc/springmvc-servlet.xml 在配置项 ...
- kettle查询-2
模糊匹配: 1.主数据/查询数据 2.模糊匹配 3.输出:jaro/jaro winkler/pair letters similarity(各自算法的匹配度measure value) http c ...