LeetCode-Roman to Integer

来源:互联网 发布:程序员思维笑话 编辑:程序博客网 时间:2024/05/21 08:53

Given a roman numeral, convert it to an integer.

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

Solution:

Code:

<span style="font-size:14px;">class Solution {public:    int getRomanValue(char c) {          switch(c) {              case 'I': return 1;               case 'V': return 5;              case 'X': return 10;              case 'L': return 50;              case 'C': return 100;              case 'D': return 500;              case 'M': return 1000;              default: return 0;          }     }            int romanToInt(string s) {        const int length = s.size();        if (length == 0) return 0;        int lastV = getRomanValue(s[0]);        int subResult = lastV;        int result = 0;        int value;        for (int i = 1; i < length; ++i) {            value = getRomanValue(s[i]);            if (value == lastV) subResult+= value;            else if (value < lastV) {                result += subResult;                lastV = value;                subResult = lastV;            } else {                subResult = value-subResult;                lastV = value;            }        }        result += subResult;        return result;    }};</span>



0 0
原创粉丝点击