首页 > 学院 > 开发设计 > 正文

50:Roman to Integer

2019-11-06 08:51:22
字体:
来源:转载
供稿:网友

题目:Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

下面解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目题目

解析:从前往后扫描字符串,逐个字符的扫描。但我们需要注意 4,9, 40,90,400,500 这 6 个数的表示,因为需要用两个罗马字符来表示这 6 个数。当我们在扫描字符串时,如果发现当前比下一个大,比如 IV = 5 - 1,这时候我们需要将这两个字符一起考虑

代码如下:

// 时间复杂度 O(n),空间复杂度 O(1)class Solution {public: inline int map(const char c) { switch (c) { case 'I' : return 1; case 'V' : return 5; case 'X' : return 10; case 'L' : return 50; case 'C' : return 100; case 'D' : return 500; case 'M' : return 1000; default : return 0; } } int romanToInt(const string& s) { int integer = 0; for (int i = 0; i < s.size(); ) { if (i != s.size() - 1 && map[s[i]] < map[s[i + 1]]) { integer += map[s[i + 1]] - map[s[i]]; ++2; } else { integer += map[s[i]] ++i; } } return integer; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表