Roman to Integer_LeetCode

Decription:

Given a roman numeral, convert it to an integer.

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

 

解题思路:

将罗马数字的字符串转换成阿拉伯数字。

先来查阅资料了解一下罗马数字的计数方法:

关键是(2)(3)两条准则。

因此主要的思想是逐个遍历字符串中的单个字符,先将当前字符代表的阿拉伯数字值加进总和中去,

再判断当前字符代表的值和上一个字符代表的值的大小,如果比上一个大,则减去上一个值的2倍。

同时,为了方便起见,用switch新定义了一个将单个罗马字符转换为数字的convert()函数。

 

 

代码:

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

 

 

 
posted @ 2017-09-12 13:41  SYSU_Bango  阅读(97)  评论(0)    收藏  举报