您的位置:首页 > 其它

LeetCode 13. Roman to Integer和12. Integer to Roman

2017-10-10 17:52 323 查看

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.

Difficulty:Easy

分析:

如果已经了解了罗马数字的表示字符及规则的话,这道题变得很简单,可以暴力破解法直接枚举每个字符,再根据字符加上对应的数字即可。

我的解法利用了STL的map,把罗马数字和标准数字存储在map中,遍历输入字符串的每一个字符,将其与后一个字符比较得出是“加上”还是“减去”,即可得出正确结果。

代码如下:

#include <iostream>
#include <map>
#include <string>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
map<char, int> m;// 利用map对应罗马数字和数字
// 罗马数字 对应 数字
char c[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
int n[] = {1, 5, 10, 50, 100, 500, 1000};
// 存储该对应关系
for (int i = 0; i < 7; i++) {
m.insert(pair<char, int>(c[i], n[i]));
}
int ans = 0;
for (int i = 0; i < s.length() - 1; i++) {
// 这里需要了解一下罗马数字的表示方法
// 比如IV表示是4,为-I+V(-1+5)
// 比如VI表示是6,为V+I(5+1)
if (m[s[i]] >= m[s[i + 1]]) {
ans += m[s[i]];
}
else {
ans -= m[s[i]];
}
}
// 不要忘记s的最后一个字符
ans += m[s[s.length() - 1]];
return ans;
}
};
int main() {
string s;
Solution so;
cin >> s;
cout << so.romanToInt(s) << endl;
return 0;
}


Similar Questions

LeetCode 12. Integer to Roman

Given an integer, convert it to a roman numeral.

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

Difficulty:Medium

分析:

首先,列举出罗马数字可能组成的表示以及对应的标准数字;

然后,利用一个循环,然后标记每个可能数字的个数,在结果字符串后加上对应的字符。

具体代码也有解释。

代码如下:

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string intToRoman(int num) {
// 列举出罗马数字可能组成的表示
string c[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
// 罗马数字可能组成的数字大小
int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

string ans;
int index = 0;
int cnt;

while (num > 0) {
// 数字的个数,例如20,为两个n[8]=10,则cnt=2,ans加了两个X
cnt = num / n[index];
while (cnt--) {
ans += c[index];
}
num %= n[index];
index++;
}
return ans;
}
};
int main() {
int num;
Solution so;
cin >> num;
cout << so.intToRoman(num) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode