15算法课程 13. Roman to Integer

来源:互联网 发布:iprint打印监控软件 编辑:程序博客网 时间:2024/05/29 03:51

Given a roman numeral, convert it to an integer.

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

solution:

1~9: {“I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”};

10~90: {“X”, “XX”, “XXX”, “XL”, “L”, “LX”, “LXX”, “LXXX”, “XC”};

100~900: {“C”, “CC”, “CCC”, “CD”, “D”, “DC”, “DCC”, “DCCC”, “CM”};

1000~3000: {“M”, “MM”, “MMM”}.

code:

class Solution  {public:     int romanToInt(string s)      {         const int N = 7;         char r[N] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};         int n[N] = {1, 5, 10, 50, 100, 500, 1000}, c[26];         for(int i = 0; i < N; ++ i)             c[r[i] - 'A'] = n[i];                  int sum = 0, l = s.length();         for(int i = 0; i < l; ++ i) {             if(i + 1 < l && c[s[i + 1] - 'A'] > c[s[i] - 'A'])             {                 sum += c[s[i + 1] - 'A'] - c[s[i] - 'A'];                 ++ i;             }             else                 sum += c[s[i] - 'A'];         }         return sum;     }};


原创粉丝点击