Roman to Integer(罗马数字转换成整数)

**Problem:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.**
*构数规则:基本字符有7个:I,V,X,L,C,D,M,分别表示1,5,10,50,100,500,1000。
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、正常使用时,连写的数字重复不得超过三次。*
*算法分析:
(1)扫描各个罗马字符,若为I X V中的任何一个则判定是否存在下一个罗马字符,若存在则比较这两个数大小,若当前数(current)小于下一个数(next),则current=next-current;并且指针加一;否则不做任何操作;
(2)结果值加上当前数,指针加一;
(3)返回结果值。*

class Solution {
public:
    int charToInt(char c){
        switch (c){
            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;
            default: return -1;
        }
    }
    int romanToInt(string s) {
        int value=0,cut=0,current,next;
        for(auto it=s.cbegin();it!=s.cend();it++){
            current=charToInt(*it);
            if(current==-1) cout<<"error"<<endl;
            if(current==1||current==10||current==100)
            if((it+1)!=s.cend()){
                next=charToInt(*(it+1));
                if(next-current>0){
                   current=next-current;
                    it++;
                }
            }
           value+=current;
        }
        return value;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值