13. Roman to Integer(C++)

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 

Solution:

 

class Solution {
public:
  int romanToInt(string s) {
    int len=s.size();
    int sum=0,i=0;
    while(i<len){
      switch(s[i]){
        case 'M': sum+=1000;break;
        case 'D': sum+=500;break;
        case 'C': if(s[i+1]=='M'||s[i+1]=='D'){
          sum-=100;
        }else{
          sum+=100;
        }
        break;
        case 'L': sum+=50; break;
        case 'X': if(s[i+1]=='L'||s[i+1]=='C'){
          sum-=10;
        }else{
          sum+=10;
        }
        break;
        case 'V': sum+=5;break;
        case 'I': if((i+1)!=len &&(s[i+1]=='V'||s[i+1]=='X')){
          sum-=1;
        }else{
          sum+=1;
        }
      }
      i++;
    }
    return sum;
  }
};

posted @   DevinGu  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示