013 Roman to Integer[E]

1 题目描述

Given a roman numeral, convert it to an integer.

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

难度:Easy

2 题目样例

无。

3 题目分析

给出罗马数字,要求输出与之对应的阿拉伯数字。

呃……题设可以说是简单粗暴的可以了。

4 思路分析

水题。

参考第12题的思路,逆向推导即可,用switch语句能让代码看起来简洁些。

注意要处理好CD,CM,XL等情况,其他均可以直接累加。

代码实现如下:

class Solution 
    
{
    
public:
    
    int romanToInt(string s)
    
    {
        int ans=0;
        
        for(int i=0;i<s.size();i++)
            
        {
            switch(s[i])
            
            {  
            
                case 'M':
                    
                    ans+=1000;
                    
                    break;  
            
                case 'D':
                    
                    ans+=500;
                    
                    break;  
            
                case 'C':
                    
                    if(i+1<s.size()&&(s[i+1]=='D'||s[i+1]=='M'))
                        
                        ans-=100;
                    
                    else 
                        
                        ans+=100;
                    
                    break;  
            
                case 'L':
                    
                    ans+=50;
                    
                    break;  
            
                case 'X':
                    
                    if(i+1<s.size()&&(s[i+1]=='L'||s[i+1]=='C'))
                        
                        ans-=10;
                    
                    else 
                        
                        ans+=10;
                    
                    break;  
            
                case 'V':
                    
                    ans+=5;
                    
                    break;  
            
                case 'I':
                    
                    if(i+1<s.size()&&(s[i+1]=='V'||s[i+1]=='X'))
                        
                        ans-=1;
                    
                    else 
                        
                        ans+=1;
                    
                    break;
            }
        }
        
        return ans;
        
    }
};

5 后记

恕我直言,这题除了让我知道了罗马字母还包含”C”,”D”等字母之外(以前我一直以为到X就截止了),毫无实际意义。

《013 Roman to Integer[E]》
《013 Roman to Integer[E]》

民意如此。(笑)

    原文作者:Lolita
    原文地址: https://zhuanlan.zhihu.com/p/33651735
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞