# 一分鐘程式設計分享 C語言 ## Leetcode 13. [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) 羅馬數字由七種字母構成,分別為 I , V , X , L , C , D 和 M。 七個字母分別代表 ``` I → 1 V → 5 X → 10 L → 50 C → 100 D → 500 M → 1,000 ``` 其規則如下 1. 若左邊字母代表之數字大於等於右邊字母代表之數字,使用加法 ``` VI = V + I = 5 + 1 = 6 MCX = M + C + X = 1000 + 100 + 10 = 10,110 ``` 1. 若左邊字母代表之數字小於右邊字母代表之數字,使用減法 ``` IV = V - I = 5 - 1 = 4 CCCXC = C * 3 + (C - X) = 100 * 3 + (100 - 10) = 390 ``` 請將以下羅馬字母轉換為阿拉伯數字(皆為單筆輸入輸出) **輸入** ``` III LVIII MCMXCIV ``` **輸出** ``` 3 58 1994 ``` ## 1. if - else 解法 ```c= int romanToInt(char* s) { int i, l = 0, nums_len=0; int sum = 0; int* nums = (int*)malloc(30 * sizeof(int)); while (s[l] != '\0') { if (s[l] == 'M') { nums[l] = 1000; } else if (s[l] == 'D') { nums[l] = 500; } else if (s[l] == 'C') { nums[l] = 100; } else if (s[l] == 'L') { nums[l] = 50; } else if (s[l] == 'X') { nums[l] = 10; } else if (s[l] == 'V') { nums[l] = 5; } else if (s[l] == 'I') { nums[l] = 1; } l++; } nums_len = l; for (i = 0; i < nums_len; i++) { if (nums[i + 1] > nums[i]) { sum -= nums[i]; } else { sum += nums[i]; } } return sum; } ``` ### Leetcode 結果 ![](https://i.imgur.com/5uHyU4V.png) ## 2. switch 解法 ```c= int romanToInt(char* s) { int i, l = 0, nums_len=0; int sum = 0; int* nums = (int*)malloc(30 * sizeof(int)); while (s[l] != '\0') { switch(s[l]) { case 'M' : nums[l] = 1000; break; case 'D' : nums[l] = 500; break; case 'C' : nums[l] = 100; break; case 'L' : nums[l] = 50; break; case 'X' : nums[l] = 10; break; case 'V' : nums[l] = 5; break; case 'I' : nums[l] = 1; break; } l++; } nums_len = l; for (i = 0; i < nums_len; i++) { if (nums[i + 1] > nums[i]) { sum -= nums[i]; } else { sum += nums[i]; } } return sum; } ``` ### Leetcode 結果 ![](https://i.imgur.com/Q5hRKQJ.png) ## 結論 由於 switch 只需判斷一次,故速度會比需一個一個判斷的 if - else 來的更快