题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
代码:
class Solution { public: int romanToInt(string s) { const int size = 7; std::map<char, int> symbol_value; char symbol_ori[size] = {‘M‘,‘D‘,‘C‘,‘L‘,‘X‘,‘V‘,‘I‘}; int value_ori[size] = {1000,500,100,50,10,5,1}; for ( size_t i = 0; i < size; ++i ) symbol_value[symbol_ori[i]]=value_ori[i]; int result = symbol_value[s[0]]; for ( size_t i = 1; i < s.size(); ++i ) { if ( symbol_value[s[i]] > symbol_value[s[i-1]] ) { result += symbol_value[s[i]] - 2*symbol_value[s[i-1]]; } else { result += symbol_value[s[i]]; } } return result; } };
tips:
根据Roman数字的构造规则:
如果当前的symbol比前一个symbol大,则当前symbol的值减去二倍之前的那个值,再累加到result中。
(为什么要减2倍,因为这个值之前已经被累加一遍了,所以减去2倍就正好了)
时间: 2024-11-05 22:55:17