(leetcode) Roman to Integer

Given a roman numeral, convert it to an integer.

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

这道题就是将罗马数字转化为一个整数,一开始做的时候很不理解,后来参考了

http://blog.sina.com.cn/s/blog_7025794a0101397g.html(ps:讲的非常好)

一开始理解最大的问题在于其中

用户输入一个数后,我们可以来遍历这个数,用result来总计和,比较i-1和i,如果,i-1比i大或者相等的话,直接相加,如果i-1小于i的话,则将总和result减去i-1这个地方数的两倍,同时加上i(因为在计算i-1时候如果i-1以及被加过一次了,而这次却要减去这个i-1,所以 需要减去2个i-1才能实现)
就相当于后边的数比左边的数大,则用右边的数减左边的数。但因为之前已经加过一次了,所以减两次。
以上就是基本思路了,下面附上代码

 

class Solution {
public:
    int toNum(const 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;
        }
        
    }
    int romanToInt(string s) {
        int result = toNum(s[0]);
        for(int i =1;i < s.length();i++)
        {
            if(toNum(s[i-1]) >= toNum(s[i]) )
            {
                result +=toNum(s[i]);
            }
            else
            {
                result = result - 2*toNum(s[i-1])+toNum(s[i]);
            }
        }
        return result;
    }
};

 

  

 

posted @ 2015-05-06 21:04  sunalive  Views(121)  Comments(0)    收藏  举报