首页 > 编程语言 > 详细

13. Roman to Integer C++

时间:2018-11-12 18:26:10      阅读:132      评论:0      收藏:0      [点我收藏+]

直接for循环,并且判断是否出现IV等情况

int which(char ch)
{
    if(ch == I)
        return 1;
    else if(ch == V)
        return 5;
    else if(ch == X)
        return 10;
    else if(ch == L)
        return 50;
    else if(ch == C)
        return 100;
    else if(ch == D)
        return 500;
    else return 1000;
}


class Solution {
public:
    int romanToInt(string s) {
        int flag = 0;
        int ans = 0;
        for(int i=0; i<s.size(); i++)
        {
            if(i != s.size()-1 && which(s.at(i)) < which(s.at(i+1)))
            {
                flag = 1;
            }
            if(flag)
            {
                ans -= which(s.at(i));
                flag = 0;
            }
            else
                ans += which(s.at(i));
        }
        cout << ans;
        return ans;
    }
};

技术分享图片

 

13. Roman to Integer C++

原文:https://www.cnblogs.com/tornado549/p/9948121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!