您的位置:首页 > 其它

刷LeetCode(13)——Roman to Integer

2017-11-21 18:15 489 查看

刷LeetCode(13)——Roman to Integer

Code it now ! https://leetcode.com/problems/roman-to-integer/description/

Given a roman numeral, convert it to an integer.

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

这题跟前面的一题刚好相反,不做过多的讨论,直接进行解题,代码如下:

#include <iostream>
#include <vector>
#include <string.h>

using namespace std;

class Solution {
public:
int romanToInt(string s) {
size_t pos = 0 ;
int sum = 0,lastindex = 0;
char* c[4][10]={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};

for( int i=3;i>=0;--i){
for( int j = 0; j<10 && c[i][j] ; ++j){
int len = strlen(c[i][j]);
if( !s.compare(pos,len,c[i][j]) ){
lastindex = j;
}
}

pos += strlen(c[i][lastindex]);

sum = 10*sum + lastindex;

}
return sum;
}
};

int main()
{
string str;
cin >> str;
cout << Solution().romanToInt(str) << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode