zoukankan      html  css  js  c++  java
  • 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;
      }
    };

  • 相关阅读:
    303. Range Sum Query
    302. Smallest Rectangle Enclosing Black Pixels
    301. Remove Invalid Parentheses
    The Swift.org Blog Welcome
    About Swift
    Swift is Open Source
    Swift is Now Open Source
    加快Terminal的打开加载速度
    加快Terminal的打开加载速度
    [note]What I’ve learnt from working on startups
  • 原文地址:https://www.cnblogs.com/devin-guwz/p/6497300.html
Copyright © 2011-2022 走看看