[leetcode-C] 13. Roman to Integer
13. Roman to Integer - C
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.
Example 1:
Input: s = "III"
Output: 3
Example 2:
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Answer 1: Accepted (Runtime: 4 ms / Memory Usage: 6.1 MB)
int romanToInt(char * s){
int i, j;
int si = 0;
int result = 0;
for(i=0;i<strlen(s);i++)
{
if(s[i] == 'I' && s[i+1] == 'V')
{
si = 4;
i++;
}
else if(s[i] == 'I' && s[i+1] == 'X')
{
si = 9;
i++;
}
else if(s[i] == 'X' && s[i+1] == 'L')
{
si = 40;
i++;
}
else if(s[i] == 'X' && s[i+1] == 'C')
{
si = 90;
i++;
}
else if(s[i] == 'C' && s[i+1] == 'D')
{
si = 400;
i++;
}
else if(s[i] == 'C' && s[i+1] == 'M')
{
si = 900;
i++;
}
else
{
switch(s[i])
{
case 'I':
si = 1;
break;
case 'V':
si = 5;
break;
case 'X':
si = 10;
break;
case 'L':
si = 50;
break;
case 'C':
si = 100;
break;
case 'D':
si = 500;
break;
case 'M':
si = 1000;
break;
}
}
result += si;
}
return result;
}
그냥 문제 그대로 조건문 도배함 V^__^V
Author And Source
이 문제에 관하여([leetcode-C] 13. Roman to Integer), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jsh5408/leetcode-C-13.-Roman-to-Integer저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)