[leetCode]Easy — Roman to Integer解題紀錄

Champion Hsieh
Firmware_Engineer
Published in
2 min readJun 22, 2021

Question:

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 one's 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.

題目翻譯:

羅馬數字呈現於七種不同的符號(標誌)I, V, X, L, C, D , M ,分別對應為下表:

標誌          值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

舉裡來說2被寫成羅馬數字II,就是兩個I疊加在一起,12被寫成XII,簡易地為X + II,而數字27被寫成XXVII,為XX + V + II

羅馬數字通常標誌從左至右會是大至小,然而羅馬數字表示4這個數值,不是IIII,取而代之的會是會被寫成IV,因為IV之前我們將5減去1表示為4。相同的原則應用於數字9會被寫成IX,這裡有六個使用減法的實例:

  • I 可以被擺在 V (5) 和X (10)之前去表示 4和 9.
  • X 可以被擺在 L (50) 和C (100) 之前去表示40 和 90.
  • C 可以被擺在D (500) 和M (1000) 之前去表示400和900.

給一個羅馬數字,請轉換成一個整數數值。

Example 1:

Input: s = "III"
Output: 3

Example 2:

Input: s = "IV"
Output: 4

Example 3:

Input: s = "IX"
Output: 9

Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution:

#include <string.h>int romanToInt(char * s){
int ans = 0;
for(int i = 0; i<strlen(s) ; i++){
if(romanToNumber(s[i+1]) > romanToNumber(s[i])){
ans -= romanToNumber(s[i]);
}else{
ans += romanToNumber(s[i]);
}
}
return ans;
}
int romanToNumber(char * c){
char x = c;
switch(x){
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default : /* Optional */
return 0;
break;
}
}

Note: 先建立一個function將各羅馬符號轉換成數值,以Switch-case的方式,並在主要轉換的function中以for迴圈做加總,並在後者值大於前者值以將前者以負值方式加總,最後回傳加總值。

--

--