zoukankan      html  css  js  c++  java
  • leetcode第13题--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.

    遍历一次输入的字符串,如果不满足类似4或者9的就直接加相应的数,否则减去相应的数。其中对应如下”IVXLCDM“对应{1,5,10,50,100,500,1000}

    class Solution {
    
    public:
    int romanToInt(string s)
    {
        string refe = "IVXLCDM";
        int val[] = {1, 5, 10, 50, 100, 500, 1000};
        int result = 0;
    
        for (int i = 0; i < s.size(); i++)
        {
            for (int j = 0; j < refe.length(); j++)
            {
                if (i+1<s.size() && s[i] == refe[j] && ((j+1<refe.size() && s[i+1] == refe[j+1]) || (j+2<refe.size() && s[i+1] == refe[j+2])))
                {result -= val[j];}
                else if (s[i] == refe[j])
                {result += val[j];}
            }
        }
        return result;
    }
    };
  • 相关阅读:
    java例题 汽油检测
    java常用api
    二分搜索法
    java例题
    java基础
    表单验证
    4.10 pm例题
    0805
    0731 框架Mybatis
    小结
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4027753.html
Copyright © 2011-2022 走看看