Description

Given a roman numeral, convert it to an integer.

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

思路

  • 这个也没啥好说的吧,首先搞清楚罗马数字是个什么鬼?
  • 基本字符:I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
  • 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3
  • 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、如:Ⅷ=8、Ⅻ=12
  • 小的数字(限于 I、X 和C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9
  • 正常使用时、连写的数字重复不得超过三次
  • 在一个数的上面画一条横线、表示这个数扩大 1000 倍。

代码

class Solution {
public:
    int romanToInt(string s) {
        int res = 0;
        int len = s.size();
        int i = 0;
        while(i < len){
            switch(s[i]){
                case 'M' : 
                    res += 1000;
                    break;
                case 'C':
                    if(i + 1 < len && (s[i + 1] == 'D' || s[i + 1] == 'M'))
                        res -= 100;
                    else res += 100;
                    break;
                case 'D':
                    res += 500;
                    break;
                case 'X':
                     if(i + 1 < len && (s[i + 1] == 'L' || s[i + 1] == 'C'))
                        res -= 10;
                    else res += 10;
                    break;
                case 'L':
                    res += 50;
                    break;
                case 'I':
                    if(i + 1 < len && (s[i + 1] == 'V' || s[i + 1] == 'X'))
                        res -= 1;
                    else res += 1;
                    break;
                case 'V':
                    res += 5;
                    break;
                default:
                    return 0;
            }
            i++;
        }
        
        return  res;
    }
};
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

3598 0元 98元 限免
3689 9.31元 9.8元 9.5折