Leetcode在线编程 roman-to-integer

Leetcode在线编程 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.


题意

将给定的罗马数字,转换成阿拉伯数字

解题思路

罗马数字构成integer-to-roman
知道罗马数字怎么组成后,这题就简单多了,
首先我们先设置数组weight和字符串tmp
sum记录罗马数字对应的阿拉伯数字
weight用来保存tmp中每个罗马数字对应的权值
然后将题目中的罗马数字进行遍历
读到的每个字母
查看是否该字母的权值是否大于前一个遍历的字母的权值,
不是的话直接sum加上字母的权值
是的话,以IV为例,首先要减去I的权值,因为在上一轮遍历已经加了,再加上IV整体的权值便是V的权值减去I的权值

AC代码

class Solution {
public:
    int romanToInt(string s) {
        int num = 0;
        int pre = 9;
        string tmp = "IVXLCDM";
        int weight[]={1,5,10,50,100,500,1000};
        for(int i = 0 ; i < s.length() ; i ++)
        {
            int ret = tmp.find(s[i]);
            if(ret > pre)
            {
               num = num - 2*weight[pre] + weight[ret];
            }
            else
                num+=weight[ret];

            pre = ret; 
        }
        return num;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值