Fork me on GitHub

[leetcode-13-Roman to Integer]

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

思路:

罗马数字有如下符号:
 
基本字符 I V X L C D M
对应阿拉伯数字 1 5 10 50 100 500 1000
计数规则:
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
  2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
  3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
  4. 正常使用时,连续的数字重复不得超过三次
  5. 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)
int romanToInt(string s)
     {
         map<char, int>T = { { 'I', 1 },
                            { 'V', 5 },
                            { 'X', 10 },
                            { 'L', 50 },
                            { 'C', 100 },
                            { 'D', 500 },
                            { 'M', 1000 }         
                            };
         int sum = T[s.back()];
         for (int i = s.length() - 2; i >= 0;i--)
         {
             if (T[s[i]]<T[s[i+1]])
             {
                 sum -= T[s[i]];
             }
             else
             {
                 sum += T[s[i]];
             }
         }
         return sum;
     }

参考:

https://discuss.leetcode.com/topic/7784/clean-o-n-c-solution

http://blog.csdn.net/wzy_1988/article/details/17057929

posted @ 2017-05-22 16:24  hellowOOOrld  阅读(110)  评论(0编辑  收藏  举报