[LeetCode] 13.Roman to Integer
2017-09-11 00:11
316 查看
[LeetCode] 13.Roman to Integer
罗马数字与阿拉伯数字的关系罗马数字的组数规则
题目描述
解题思路
实验代码
罗马数字与阿拉伯数字的关系
基本字符 | 相应的阿拉伯数字 |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
罗马数字的组数规则
1.基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;2.不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个。
题目描述
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
解题思路
与第12题类似,道理是相同的,只不过是反着来而已。所以解题思路在了解了罗马数字的特点以及其和阿拉伯数字的关系之后也很快能出来。这次我选择使用了map容器解决问题,因为感觉用字符表示相应的阿拉伯数字更加方便也更加有效。
实验代码
class Solution { public: int romanToInt(string s) { int l = s.length(); if (l == 0) return 0; map<char, int> m; m['M'] = 1000; m['D'] = 500; m['C'] = 100; m['L'] = 50; m['X'] = 10; m['V'] = 5; m['I'] = 1; int integer = m[s[l-1]]; for (int i = l-2; i >= 0; i--) { if (m[s[i+1]] <= m[s[i]]) integer += m[s[i]]; else integer -= m[s[i]]; } return integer; } };
相关文章推荐
- leetcode 13 Roman to Integer
- leetcode-13:Roman to Integer
- [LeetCode][13]Roman to Integer解析 罗马字符转int类型关于栈的常数实现-Java实现
- leetcode-13 Roman to Integer
- LeetCode(13)-- RomanToInteger
- leetcode Roman to Integer(13)
- LeetCode 13 -Roman to Integer ( JAVA )
- leetcode 12 interger to Roman && 13 Roman to Integer
- Leetcode 13 Roman to Integer
- [leetcode-13]Roman to Integer(C)
- LeetCode13 Roman to Integer
- 【leetcode】【13】Roman to Integer
- LeetCode 12-13:Integer to Roman&&Roman to Integer
- Leetcode_13_Roman to Integer
- 【LeetCode】C# 13、Roman to Integer
- LeetCode 13 - Roman to Integer
- Java [leetcode 13] Roman to Integer
- LeetCode 13: Roman to Integer
- leetcode13: Roman to Integer
- [leetcode] 13. Roman to Integer