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.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
- 1 <= s.length <= 15
- s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
- It is guaranteed that s is a valid roman numeral in the range [1, 3999].
이 문제는 주어진 로마숫자 표기를 아라비안숫자로 변환하는 것이다.
로마 숫자는 I, V, X, L, C, D, M 과 2개의 연속된 숫자의 순서를 잘 조합하여 조건을 만들면 된다.
class Solution:
def romanToInt(self, s):
answer = 0
for c in range(0, len(s)):
if s[c].__eq__("I"):
if c == len(s)-1:
answer += 1
elif s[c+1].__eq__("V") or s[c+1].__eq__("X"):
answer -= 1
else:
answer += 1
elif s[c].__eq__("V"):
answer += 5
elif s[c].__eq__("X"):
if c == len(s)-1:
answer += 10
elif s[c+1].__eq__("L") or s[c+1].__eq__("C"):
answer -= 10
else:
answer += 10
elif s[c].__eq__("L"):
answer += 50
elif s[c].__eq__("C"):
if c == len(s)-1:
answer += 100
elif s[c+1].__eq__("D") or s[c+1].__eq__("M"):
answer -= 100
else:
answer += 100
elif s[c].__eq__("D"):
answer += 500
elif s[c].__eq__("M"):
answer += 1000
else:
break;
return answer
문제 출처 : https://leetcode.com/problems/roman-to-integer/
Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_13.py
'IT > LeetCode' 카테고리의 다른 글
[LeetCode] 20. Valid Parentheses (0) | 2022.07.21 |
---|---|
[LeetCode] 14. Longest Common Prefix (0) | 2022.07.21 |
[LeetCode] 9. Palindrome Number (0) | 2022.07.20 |
[LeetCode] 7. Reverse Integer (0) | 2022.07.20 |
[LeetCode] 5. Longest Palindromic Substring (0) | 2022.07.20 |
댓글