Roman to Integer

Roman to Integer 

Given a roman numeral, convert it to an integer.

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

Solution:

一种很粗暴的解法,罗列所有可能出现的情况:
class Solution {
public:
    int romanToInt(string s) {
        int total = 0;
        for (int a = 0; a < s.length(); a++)
        {
            if (s[a] == 'I')
            {
                if (s[a+1] == 'V')
                {
                    total += 4;
                    a++;
                }
                else if (s[a+1] == 'X')
                {
                    total += 9;
                    a++;
                }
                else
                {
                    total += 1;
                }
            }
            else if (s[a] == 'X')
            {
                if (s[a+1] == 'L')
                {
                    total += 40;
                    a++;
                }
                else if (s[a+1] == 'C')
                {
                    total += 90;
                    a++;
                }
                else
                {
                    total += 10;
                }
            }
            else if (s[a] == 'C')
            {
                if (s[a+1] == 'D')
                {
                    total += 400;
                    a++;
                }
                else if (s[a+1] == 'M')
                {
                    total += 900;
                    a++;
                }
                else
                {
                    total += 100;
                }
            }
            else if (s[a] == 'V') total += 5;
            else if (s[a] == 'L') total += 50;
            else if (s[a] == 'D') total += 500;
            else if (s[a] == 'M') total += 1000;
        }
        return total;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值