LeetCode13. 罗马数字转整数

题目

分析

受LeetCode 12题目影响,一时没反应过来用哈希存储,虽说难度是简单,还没上一道做的舒服。。。。

这道题目关键在于特判下4的特殊情况,就是后一个字母比当前字母要大时情况要特殊判断下

代码

复制代码
 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4 
 5         unordered_map<char,int>m;
 6         m['M'] = 1000;
 7         m['D'] = 500;
 8         m['C'] = 100;
 9         m['L'] = 50;
10         m['X'] = 10;
11         m['V'] = 5;
12         m['I'] = 1;
13 
14         int res  = 0;
15         for(int i = 0; i < s.size();i++){
16             //cout<<s[i] << " "<<s[i+1] << " "<<m[s[i]] << " "<< m[s[i+1]]<<endl;
17             if(m[s[i]] < m[s[i+1]] && i < s.size() -1){
18                 res += (m[s[i+1]] - m[s[i]]);
19                 i = i + 1;
20             }else{
21                 res += m[s[i]];
22             }
23             //cout<<res<<endl;
24             
25         }
26         return res;
27     }
28 };
复制代码

 

y总:

复制代码
class Solution {
public:
    int romanToInt(string s) {

        unordered_map<char,int>m;
        m['M'] = 1000;
        m['D'] = 500;
        m['C'] = 100;
        m['L'] = 50;
        m['X'] = 10;
        m['V'] = 5;
        m['I'] = 1;

        int res  = 0;
        for(int i = 0; i < s.size();i++){
            if(m[s[i]] < m[s[i+1]] && i < s.size() -1){
                res -= m[s[i]];
            }else{
                res += m[s[i]];
            }
            
        }
        return res;
    }
};
复制代码

 

posted @   Uitachi  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示