[leetcode] 13. Roman to Integer
来源:互联网 发布:淘宝网店怎么激活 编辑:程序博客网 时间:2024/06/05 17:46
题目链接: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.
思路
罗马数字总共有七个 即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。其数字之间可以组合来表示任意的数字,但是不可以进行运算。
其组合规律如下:
左加右减:
较大的罗马数字右边记上较小的罗马数字,表示大数加小数
较大的罗马数字左边记上较小的罗马数字,表示大数减小数
左减的数字只限于I、X、C
左减时不可以跨位,如果99不可以写成IC,只能写成XCIX
左减只能有一位。如8写成VIII,而非IIX
右加最多三位。如14写成XIV,而非XIIII
OK,基本的规则就这些。
class Solution { public: int romanToInt(string s) { hash['I'] = 1; hash['V'] = 5; hash['X'] = 10; hash['L'] = 50; hash['C'] = 100; hash['D'] = 500; hash['M'] = 1000; int cnt = 0; for(int i =0; i< s.size(); i++) { cnt += hash[s[i]]; if(i>0 && hash[s[i]] > hash[s[i-1]]) cnt -= 2* hash[s[i-1]]; } return cnt; } private: unordered_map<char, int> hash; };
阅读全文
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
- 数据结构-排序进阶代码
- Collections 工具类
- Eclipse 版本发布规律
- python中input()和raw_input的区别
- E
- [leetcode] 13. Roman to Integer
- 2017年12月16日 第三十八天次总结
- Nginx的反向代理与负载均衡
- Median of Two Sorted Arrays
- 线性表- 常出的bug总结
- 使用Python实现简单主机批量管理工具
- 要点提炼|开发艺术之Window
- 设计模式——职责链模式
- 使用ACE_Get_Opt解析命令行