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;
    }
  • 相关阅读:
    java程序员裸机配置
    安装库
    自定义脚本模板
    Oracle数据库触发器简单案例
    Oracle数据库按正则切割字符串
    Oracle查询一张表的所有字段
    Oracle数据库系统表
    Oracle设置最大连接数
    Oracle博客参考教程
    区间dp [H
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5103763.html
Copyright © 2011-2022 走看看