{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "810f4644697941d9894b88099b1bd39c", "keywords": "哈希表,数学,字符串", "title": "罗马数字转整数", "desc": [ { "content": "\n
\n

罗马数字包含以下七种字符: I, V, X, LCD 和 M。\n

", "language": "markdown" }, { "content": "\n
字符          数值\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000
", "language": "markdown" }, { "content": "\n

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12\n写做 XII ,即为 X + II 。 27\n写做  XXVII,\n即为 XX + V + II 。

", "language": "markdown" }, { "content": "\n

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5\n减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

", "language": "markdown" }, { "content": "\n", "language": "markdown" }, { "content": "\n

给你一个整数,将其转为罗马数字。

", "language": "markdown" }, { "content": "\n

 

", "language": "markdown" }, { "content": "\n

示例 1:

", "language": "markdown" }, { "content": "\n
输入: num = 3\n
输出:
\"III\"
", "language": "markdown" }, { "content": "\n

示例 2:

", "language": "markdown" }, { "content": "\n
输入: num = 4\n
输出:
\"IV\"
", "language": "markdown" }, { "content": "\n

示例 3:

", "language": "markdown" }, { "content": "\n
输入: num = 9\n
输出:
\"IX\"
", "language": "markdown" }, { "content": "\n

示例 4:

", "language": "markdown" }, { "content": "\n
输入: num = 58\n
输出:
\"LVIII\"\n
解释:
L = 50, V = 5, III = 3.\n
", "language": "markdown" }, { "content": "\n

示例 5:

", "language": "markdown" }, { "content": "\n
输入: num = 1994\n
输出:
\"MCMXCIV\"\n
解释:
M = 1000, CM = 900, XC = 90, IV = 4.
", "language": "markdown" }, { "content": "\n

 

", "language": "markdown" }, { "content": "\n

提示:

", "language": "markdown" }, { "content": "\n\n
", "language": "markdown" } ], "answer": [ { "content": "", "language": "python" } ], "prepared": [ [ { "content": "", "language": "python" } ], [ { "content": "", "language": "python" } ], [ { "content": "", "language": "python" } ] ], "template": { "content": "class Solution:\n\tdef romanToInt(self, s: str) -> int:\n\t\tunits = [\n\t\t\t[\"M\", 1000, 1],\n\t\t\t[\"CM\", 900, 2],\n\t\t\t[\"D\", 500, 1],\n\t\t\t[\"CD\", 400, 2],\n\t\t\t[\"C\", 100, 1],\n\t\t\t[\"XC\", 90, 2],\n\t\t\t[\"L\", 50, 1],\n\t\t\t[\"XL\", 40, 2],\n\t\t\t[\"X\", 10, 1],\n\t\t\t[\"IX\", 9, 2],\n\t\t\t[\"V\", 5, 1],\n\t\t\t[\"IV\", 4, 2],\n\t\t\t[\"I\", 1, 1]\n\t\t]\n\t\tend = len(s)\n\t\tstart = 0\n\t\ti = 0\n\t\tr = 0\n\t\twhile i < len(units):\n\t\t\tunit = units[i][0]\n\t\t\tvalue = units[i][1]\n\t\t\tstep = units[i][2]\n\t\t\tif end-start >= step and s[start:start+step] == unit:\n\t\t\t\tr += value\n\t\t\t\tstart += step\n\t\t\telse:\n\t\t\t\ti += 1\n\t\treturn r\n# %%\ns = Solution()\nprint(s.romanToInt(\"III\"))", "language": "python" }, "node_id": "dailycode-97cf74ce017444f1aa65cfa6a8ae7451", "license": "csdn.net", "created_at": 1637894161, "topic_link": "https://bbs.csdn.net/topics/600470218" }