✍️

【C言語】Leet Code Probrems「13. Roman to Integer」解答例

2023/01/08に公開

はじめに
本記事ではLeetCodeのProblemの解答例を示す

問題
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

https://leetcode.com/problems/roman-to-integer/

解答例

int romanToInt(char * s){

    int value[100];
    int sum=0;

    memset(value,0,sizeof value);

    for(int i=0;s[i]!='\0';i++){
        switch(s[i]){
            case 'I':
                value[i]=1;
                break;
            case 'V':
                value[i]=5;
                break;
            case 'X':
                value[i]=10;
                break;
            case 'L':
                value[i]=50;
                break;           
            case 'C':
                value[i]=100;
                break;           
            case 'D':
                value[i]=500;
                break;           
            case 'M':
                value[i]=1000;
                break;                     
            defalut:
                break;
        }
    }

    for(int i=0;value[i]!=0;i++){
        if(value[i]<value[i+1]){
            sum+=value[i+1]-value[i];
            i++;
        }else{
            sum+=value[i];
        }
    }
    
    return sum;
}

時間が掛かった箇所
①switch文のbreakを書き忘れるミス…switch文に慣れていないのが問題だった
②文字列を数値にする箇所と、数値の和を計算する箇所のfor文の終了条件を決めるのに時間がかかった
文字列を数値に変換する箇所は、文字列の終端にnull文字('\0')が挿入されるので、そこまでループを回せばよい。
数値の和を計算する箇所は、値が0の箇所が終端として、そこまでループを回すようにした。
最初、配列valueの初期化をしておらず、不定値が代入されていて期待結果が得られなかったのでmemsetで0初期化するようにしたところ期待結果が得られた。

まとめ
・変数、配列の初期化は確実に行うこと。
・switch文にはbreakを必ず記述すること。バグの原因になる。

Discussion