您的位置:首页 > 其它

【LeetCode 13】 Roman to Integer

2017-02-21 22:31 471 查看
/****************************
LeetCode 13 Roman to Integer

Given a roman numeral, convert it to an integer.

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

int romanToInt(string s) {
if (s.size()<1)
{
return 0;
}
//使用hashmap更合适
int weight[26];
memset(weight, 0, sizeof(weight));
weight['I' - 'A'] = 1;
weight['V' - 'A'] = 5;
weight['X' - 'A'] = 10;
weight['L' - 'A'] = 50;
weight['C' - 'A'] = 100;
weight['D' - 'A'] = 500;
weight['M' - 'A'] = 1000;
int size = s.size();
int pivot = weight[s.at(size - 1) - 'A'];
int result = pivot;
for (int ii = size - 2; ii >= 0; ii--)
{
int cur = weight[s[ii] - 'A'];
if (cur >= pivot) //  加上该位上值
{
result += cur;
pivot = cur;
}
else      //减去该位上的值
{
result -= cur;
pivot = cur;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: