LeetCode | Roman to Integer(罗马数字转换成整数)


Given a roman numeral, convert it to an integer.

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

题目解析:

这道题还是跟上题一样,要对罗马数字有一定了解,并且有一定的技巧。不过解题方法有点缺陷,就是不会检查输入的正确与否,比如“XXXXX”,也会正常输出50。

题目的思路是从n-1个字符开始向前遍历,当碰到I,V,X等就相应的加上数字,注意,这里不需要再乘以位数了。因为其代表的含义是一定的。如果str[i] < str[i+1],那么就要减去str[i],比如IX,其结果是10-1=9。知道这个技巧了,就容易写代码了。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int RomanToInteger(char *str);

int main()
{
    char buf[20];

    while(scanf("%s",buf) == 1){
        int res = RomanToInteger(buf);
        printf("%d\n",res);

    }
    return 0;
}

int RomanToInteger(char *str)
{
    int result = 0;
    int n = strlen(str);
    int arr[26];
    arr['I'-'A'] = 1;
    arr['V'-'A'] = 5;
    arr['X'-'A'] = 10;
    arr['L'-'A'] = 50;
    arr['C'-'A'] = 100;
    arr['D'-'A'] = 500;
    arr['M'-'A'] = 1000;

    result = arr[str[n-1]-'A'];
    for(int i = n-2;i >= 0;--i){
        if(arr[str[i]-'A'] >= arr[str[i+1]-'A'])
            result = result + arr[str[i]-'A'];
        else
            result = result - arr[str[i]-'A'];
    }
    return result;
}

还有一种方法是,从0–>n-1遍历。这就要同理也要判断相应的大小即可。其结果是一样的,因为确定的数字I,V,X等,都有确定的数据。

int RomanToInteger(char *str)
{
    int result = 0;
    int n = strlen(str);
    int arr[26];
    arr['I'-'A'] = 1;
    arr['V'-'A'] = 5;
    arr['X'-'A'] = 10;
    arr['L'-'A'] = 50;
    arr['C'-'A'] = 100;
    arr['D'-'A'] = 500;
    arr['M'-'A'] = 1000;

    result = arr[str[n-1]-'A'];
    for(int i = 0;i < n-1;++i){
        if(arr[str[i]-'A'] >= arr[str[i+1]-'A'])
            result = result + arr[str[i]-'A'];
        else
            result = result - arr[str[i]-'A'];
    }
    return result;
}

点赞