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

    Subscribe to see which companies asked this question

    Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000)

    规则:位于大数的后面时就作为加数;位于大数的前面就作为减数

    如:Ⅲ=3,Ⅳ=4,Ⅵ=6,ⅩⅨ=19,ⅩⅩ=20,ⅩLⅤ=45,MCMⅩⅩC=1980

    从最低位开始,如果前面的数比它大,则让前面的数值加后面的数值,如果比它小,则让当前数值减去前面的数值

    int romanToInt(string s) {
        if (s.length() == 0) return 0;
        int len = s.length();
        unordered_map<char, int> map;
        map.insert(make_pair('I', 1));
        map.insert(make_pair('V', 5));
        map.insert(make_pair('X', 10));
        map.insert(make_pair('L', 50));
        map.insert(make_pair('C', 100));
        map.insert(make_pair('D', 500));
        map.insert(make_pair('M', 1000));
        int result = map.at(s.at(len - 1));
        int pivot = result;
        for (int i = len - 2; i >= 0; i--) {
            int curr = map.at(s.at(i));
            if (curr >= pivot) {
                result += curr;
            }
            else {
                result -= curr;
            }
            pivot = curr;
        }
        return result;
    }
  • 相关阅读:
    js日期 操作
    c# 调用c++ dll
    多维数组与交错数组的转换
    c++多态
    c++ 指向类成员函数的函数指针
    c++虚析构函数的使用及其注意点
    c++模板实现 linq
    Php 常用类
    Php ORM 对象关系映射
    Php OpenID
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5103763.html
Copyright © 2011-2022 走看看