欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】13. Roman to Integer

发布时间:2025/5/22 编程问答 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode】13. Roman to Integer 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

提示:

此题只要熟悉罗马数字的书写语法,做起来就不会太难,关于罗马数字的介绍可以参考这里。

代码:

从左往右转换的方法:

class Solution { public:int value(char c) {if (c == 'I') return 1;if (c == 'X') return 10;if (c == 'C') return 100;if (c == 'M') return 1000;if (c == 'V') return 5;if (c == 'L') return 50;if (c == 'D') return 500;}int romanToInt(string s) {if (s.size() == 0) return 0;if (s.size() == 1) return value(s[0]);int current, next, sum = 0, i = 0;for (; i < s.size() - 1; ++i) {current = value(s[i]);next = value(s[i+1]);sum += current < next ? -current : current;}sum += value(s[i]);return sum;} };

从右往左转换的方法:

class Solution { public:int romanToInt(string s) {int res = 0;for (int i = s.length() - 1; i >= 0; i--) {char c = s[i];switch (c) {case 'I':res += (res >= 5 ? -1 : 1);break;case 'V':res += 5;break;case 'X':res += 10 * (res >= 50 ? -1 : 1);break;case 'L':res += 50;break;case 'C':res += 100 * (res >= 500 ? -1 : 1);break;case 'D':res += 500;break;case 'M':res += 1000;break;}}return res;} };

转载于:https://www.cnblogs.com/jdneo/p/4755197.html

总结

以上是生活随笔为你收集整理的【LeetCode】13. Roman to Integer的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。