Leetcode#13:romanToInt 暑假训练第一弹

来源:互联网 发布:基金有什么软件 编辑:程序博客网 时间:2024/06/16 12:24

长时间未没有练习,生疏了太多。

语言不够简洁,慢慢来吧

Given a roman numeral, convert it to an integer.

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


#include <iostream>#include <cstring>#include <algorithm>using namespace std; int romanToInt(string s) {        int ans = 0;        int s1[20]={0};        for (int i = 0; i < s.length(); i++){            if(s[i]=='I')                s1[i]=1;            if(s[i]=='V')                s1[i]=5;            if(s[i]=='X')                s1[i]=10;            if(s[i]=='L')                s1[i]=50;            if(s[i]=='C')                s1[i]=100;            if(s[i]=='D')                s1[i]=500;            if(s[i]=='M')                s1[i]=1000;            else                    ;        }        if(s.length()==1)        ans = ans+s1[0];       if(s.length()>1){        for (int i = 0; i < (s.length()-1); i++){            if(s1[i]<s1[i+1])                ans = ans - s1[i];            else                ans = ans + s1[i];        }        ans = ans + s1[(s.length()-1)];       }         return ans;    }    int main(){    string s;    cin>>s;    cout <<romanToInt(s)<<endl;    return 0;}


0 0