LeetCode 13. Roman to Integer
来源:互联网 发布:电脑怎么发布淘宝宝贝 编辑:程序博客网 时间:2024/05/16 05:06
题目链接:https://leetcode.com/problems/roman-to-integer/
题目内容:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目分析:先去某度科普下罗马数字,然后遍历字符串的每个字符,分两种情况:1)一般来说字符越往后,对应的数字越小,至少是不大于,比如MM, VII等等,这种情况下直接从左到右累加就可以; 2)但是有几个特殊的数,类似在4,9, 40, 90, 400, 900这样的数字,罗马数字的规律是由两个字符ab构成,而b对应的数字比a的大,这种情况下实际得到的值为(b-a),但由于a在b的前面,在遍历a的时候已经被累加进最后结果,因此要再减去被“误加”的这部分,因此遍历到b的时候加上的值应该为(b-2*a)
class Solution {public: int romanToInt(string s) { if(s.size() == 0) return 0; int len = s.size(); int sum = ch2int(toupper(s[0])); for(int i = 1; i < len; ++i) { int last = ch2int(toupper(s[i - 1])); int cur = ch2int(toupper(s[i])); if(last < cur) sum += cur - 2 * last; else sum += cur; } return sum; } int ch2int(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } }};
0 0
- LeetCode 13. Roman to Integer
- [LeetCode]13.Roman to Integer
- LeetCode --- 13. Roman to Integer
- [Leetcode] 13. Roman to Integer
- [leetcode] 13.Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- [LeetCode]13. Roman to Integer
- Leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- LeetCode *** 13. Roman to Integer
- LeetCode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- 【LeetCode】13. Roman to Integer
- Leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- UIImage的各种处理(旋转,压缩,写入,读去,计算大小)等和方法的区别的介绍
- svg文本动态改变后字体设置丢失问题
- secure crt连接oracle 解决oracle账户锁定问题,并配置weblogic数据源
- Passwordless SSH Login
- PHP时间日期操作增减(date strtotime) 加一天 加一月
- LeetCode 13. Roman to Integer
- common-compress压缩解压文件
- PHP记录网站运行时间?
- 王爽汇编实验9
- 大话设计模式系列目录
- 第一课:ARM底层开发笔记之ARM基础概念
- 剑指Offer--018-树的子结构(判断B树是不是A树的一颗子树)
- 统计信息自动更新导致查询超时
- 关于UILable自适应数据内容问题