您的位置:首页 > 其它

LeetCode : Roman to Integer

2012-12-06 16:34 323 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

其实一个一个加就行,例如IV是4,但直接加的结果是6,这个时候减去2就行。

class Solution {
public:
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<char, int> roman;
roman.insert(make_pair('I', 1));
roman.insert(make_pair('V', 5));
roman.insert(make_pair('X', 10));
roman.insert(make_pair('L', 50));
roman.insert(make_pair('C', 100));
roman.insert(make_pair('D', 500));
roman.insert(make_pair('M', 1000));

int n = s.size();
int pre = 10000;
int res = 0;
int cur = 0;
for(int i = 0 ;i < n; ++i){
cur = roman[s[i]];
res += cur;
if(cur > pre){
res -= 2*pre;
}
pre = cur;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: