首页 > 代码库 > leetcode第13题--Roman to Integer

leetcode第13题--Roman to Integer

Problem:

Given a roman numeral, convert it to an integer.

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

遍历一次输入的字符串,如果不满足类似4或者9的就直接加相应的数,否则减去相应的数。其中对应如下”IVXLCDM“对应{1,5,10,50,100,500,1000}

class Solution {public:int romanToInt(string s){    string refe = "IVXLCDM";    int val[] = {1, 5, 10, 50, 100, 500, 1000};    int result = 0;    for (int i = 0; i < s.size(); i++)    {        for (int j = 0; j < refe.length(); j++)        {            if (i+1<s.size() && s[i] == refe[j] && ((j+1<refe.size() && s[i+1] == refe[j+1]) || (j+2<refe.size() && s[i+1] == refe[j+2])))            {result -= val[j];}            else if (s[i] == refe[j])            {result += val[j];}        }    }    return result;}};

 

leetcode第13题--Roman to Integer