本文主要是介绍【LeetCode算法练习(C++)】Roman to Integer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
链接:Roman to Integer
解法:用数组存字母表示的数
class Solution {
public: int romanToInt(string s) { int ans = 0, len = s.length(), val[255]; val['I'] = 1;val['V'] = 5;val['X'] = 10;val['L'] = 50; val['C'] = 100;val['D'] = 500;val['M'] = 1000;for (int i = 0; i < len; i++) { if (i > 0 && val[s[i]] > val[s[i - 1]]) { ans += val[s[i]] - 2 * val[s[i - 1]]; } else { ans += val[s[i]]; } } return ans;}
};
Runtime: 119 ms
这篇关于【LeetCode算法练习(C++)】Roman to Integer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!