[leetcode]13. Roman to Integer

来源:互联网 发布:js旋转木马效果 编辑:程序博客网 时间:2024/05/23 17:46

Given a roman numeral, convert it to an integer.

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

int trans(char in){    switch(in)    {        case 'I':return 1;        case 'V':return 5;        case 'X':return 10;        case 'L':return 50;        case 'C':return 100;        case 'D':return 500;        case 'M':return 1000;        default:return 0;    }}int romanToInt(char* s) {    char roman[7]={'I','V','X','L','C','D','M'};    int result = 0;    char tmp;    int mul;    for(int i=0; i<strlen(s); i++)    {        if(i==strlen(s)-1)            tmp=NULL;        else            tmp=s[i+1];        mul=1;        if((s[i]==roman[0]) || (s[i]==roman[2]) || (s[i]==roman[4]))        {            if((s[i]==roman[0]) && ((tmp==roman[1])||(tmp==roman[2])))                mul=-1;            if((s[i]==roman[2]) && ((tmp==roman[3])||(tmp==roman[4])))                mul=-1;            if((s[i]==roman[4]) && ((tmp==roman[5])||(tmp==roman[6])))                mul=-1;        }        result+= trans(s[i]) * mul;    }    return result;}


0 0