1. 程式人生 > >LeetCode | Roman to Integer(羅馬數字轉換成整數)

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;
}