leetcode:Roman to Integer

来源:互联网 发布:jira mysql驱动 win7 编辑:程序博客网 时间:2024/06/03 19:06

Given a roman numeral, convert it to an integer.

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

Subscribe to see which companies asked this question


class Solution {        int getNum(char c)    {        if (c == 'M')            return 1000;        if (c == 'D')            return 500;        if (c == 'C')            return 100;        if (c == 'L')            return 50;        if (c == 'X')            return 10;        if (c == 'V')            return 5;        if (c == 'I')            return 1;    }    public:    int romanToInt(string s) {                int total = 0;        int curNum = 0;        int preNum = 0;        int count = 0;                for (int i=0; i<s.size(); i++)        {            curNum = getNum(s[i]);                        if (curNum == preNum)            {                count++;                total += curNum;            }            else            {                if (preNum != 0 && curNum > preNum)                {                    total = total-2*preNum*count;                }                total += curNum;                preNum = curNum;                count = 1;            }        }                return total;            }};


0 0
原创粉丝点击