Roman to Integer leetcode

Given a roman numeral, convert it to an integer.

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

题目的意思是将给定的罗马数字转换为一个整数

什么是罗马数字:

I, II, III, IV, V, VI, VII, VIII, IX, X.

上面的罗马数字表示为 1  2   3   4   5  6  7  8 9 10


在罗马数字中,各个字符对应的数字大小如上,级别最高的字符为M  其次为D    最小的为I

规则:
从右往左,遇到比上一个字符级别低的或者相同的就 加上该字符对应的数字值   表示   和累加  如VII  为  1+ 1+ 5  =7
遇到一个比上一个字符级别高就减去该字符对应的数字值,如  IV  为  5 -1=4
代码如下:
<span style="font-size:18px;">class Solution {
public:

    /*
    Symbol	Value
    I	1
    V	5
    X	10
    L	50
    C	100
    D	500
    M	1,000
    */
    //需要注意 罗马数字中存在减法,从后往前遍历
    int romanToInt(string s) {
        
    int result=0;
    //要记录上一次出现的是哪个单位,用数字记录上一次出现的是哪个单位,分别为 1 2 3 4 5 6 7 表示 I V X L C D M
    int last_show=0;//初始值为0  当上一次出现的值小于等于当前值时用加法,否则有减法
    int cur_show; //当前值
    for(int i=s.length()-1;i>=0;i--)
    {
        
        switch(s[i])
        {
            case 'I':
                cur_show=1;
                if(cur_show>=last_show)
                    result+=1;
                else
                    result-=1;
                break;
                
            case 'V':
                cur_show=2;
                if(cur_show>=last_show)
                    result+=5;
                else
                    result-=5;
                break;
                
            case 'X':
               cur_show=3;
               if(cur_show>=last_show)
                    result+=10;
                else
                    result-=10;
                break;
                
             case 'L':
                cur_show=4;
                if(cur_show>=last_show)
                    result+=50;
                else
                    result-=50;
                break;
                
            case 'C':
                cur_show=5;
                if(cur_show>=last_show)
                    result+=100;
                else
                    result-=100;
                break;
                
            case 'D':
                cur_show=6;
                if(cur_show>=last_show)
                    result+=500;
                else
                    result-=500;
                break;
            case 'M':
                cur_show=7;
                if(cur_show>=last_show)
                    result+=1000;
                else
                    result-=1000;
                break;
            default:
                break;                    
        }
        last_show=cur_show;
    }
        return result;
    }
};</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值