LeetCode 13. 罗马数字转整数
2018-03-28 23:09
295 查看
题目描述: 罗马数字转整数
给定一个罗马数字,将其转换成整数。 返回的结果要求在 1 到 3999 的范围内。 图转自https://www.douban.com/note/335254352/解题思路:
观察可知,前面一个数字比后面一个数字小,就用ans减去前面的数字,其余情况全是加法。代码:
class Solution {public:
int romanToInt(string s) {
map<char, int> m;
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int ans = 0;
for(int i = 0 ; i < s.length() - 1 ; i ++) {
if(m[s[i]] < m[s[i+1]]) ans -= m[s[i]];
else ans += m[s[i]];
}
ans += m[s[s.length() - 1]];
return ans;
}
};
相关文章推荐
- LeetCode习题笔记——罗马数字和整数之间的转换
- LeetCode - 13. 罗马数字转整数
- [LeetCode]12. Integer to Roman(整数转化为罗马数字)
- [Leetcode] Roman to integer 罗马数字转成整数
- LeetCode 12 Integer to Roman (整数转罗马数字)
- leetcode-java.T013_RomarToInteger 罗马数字转成整数数字
- [Leetcode] Interger to roman 整数转成罗马数字
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- LeetCode : 12 整数转罗马数字 C++
- leetcode:Integer to Roman(整数转化为罗马数字)
- [LeetCode] 12. Integer to Roman 整数转为罗马数字
- python解leetcode——13.Roman to Integer (罗马数字转为整数)
- 【LeetCode-面试算法经典-Java实现】【013-Roman to Integer (罗马数字转成整数)】
- leetcode 罗马数字与整数的转换算法
- [LeetCode] 13. Roman to Integer 罗马数字转为整数
- LeetCode-13罗马数字转整数
- Leetcode 13 Roman to Integer 罗马数字转整数
- Leetcode : 13 罗马数字转整数
- [LeetCode] Integer to Roman 整数转化成罗马数字
- LeetCode | Integer to Roman(整数转换成罗马数字)