• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
13. Roman to Integer C++

直接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;
    }
};

 

posted on 2018-11-12 18:11  549  阅读(86)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3