Leetcode在线编程roman-to-integer

来源:互联网 发布:模拟炒股哪个软件好 编辑:程序博客网 时间:2024/05/17 01:00

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
原创粉丝点击