|
@@ -0,0 +1,54 @@
|
|
|
+import unittest
|
|
|
+from typing import List
|
|
|
+class Solution:
|
|
|
+ def romanToInt(self, x: str) -> int:
|
|
|
+ roman = {'I':1
|
|
|
+ ,'V':5
|
|
|
+ ,'X':10
|
|
|
+ ,'L':50
|
|
|
+ ,'C':100
|
|
|
+ ,'D':500
|
|
|
+ ,'M':1000
|
|
|
+ }
|
|
|
+ num = 0
|
|
|
+ last_num = 0
|
|
|
+ for i in range(len(x)):
|
|
|
+ if roman[x[i]] <= last_num:
|
|
|
+ num = num + roman[x[i]]
|
|
|
+ else:
|
|
|
+ num = num + roman[x[i]] - 2 * last_num
|
|
|
+ last_num = roman[x[i]]
|
|
|
+ return num
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+class TestromanToInt(unittest.TestCase):
|
|
|
+ def test_romanToInt(self):
|
|
|
+ x = "III"
|
|
|
+ s = Solution()
|
|
|
+ res = s.romanToInt(x)
|
|
|
+ self.assertEqual(res, 3)
|
|
|
+ def test_romanToInt2(self):
|
|
|
+ x = "IV"
|
|
|
+ s = Solution()
|
|
|
+ res = s.romanToInt(x)
|
|
|
+ self.assertEqual(res, 4)
|
|
|
+ def test_romanToInt3(self):
|
|
|
+ x = "IX"
|
|
|
+ s = Solution()
|
|
|
+ res = s.romanToInt(x)
|
|
|
+ self.assertEqual(res, 9)
|
|
|
+
|
|
|
+ def test_romanToInt4(self):
|
|
|
+ x = "LVIII"
|
|
|
+ s = Solution()
|
|
|
+ res = s.romanToInt(x)
|
|
|
+ self.assertEqual(res, 58)
|
|
|
+
|
|
|
+ def test_romanToInt5(self):
|
|
|
+ x = "MCMXCIV"
|
|
|
+ s = Solution()
|
|
|
+ res = s.romanToInt(x)
|
|
|
+ self.assertEqual(res, 1994)
|
|
|
+
|