算法 - 罗马数字和整型的相互转换
罗马符号 | 对应数字 |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
基本规则:
小数+大数:后者减前者,但不可跨越一个位值,如 8(VIII)不能是IIX
大数+小数:两者相加,但右加数字不可连续超过三位,如9(IX)不能是VIIII
1、Roman To Integer
class Solution {
public:
/**
* @param s: Roman representation
* @return: an integer
*/
int romanToInt(string &s) {
// write your code here
int n = s.length();
if(n==0)
return 0;
map<char, int> m;
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int ans = 0;
for(int i=0; i<n; i++){
if(i+1<n && m[s[i]]<m[s[i+1]]){
ans -= m[s[i]];
}else{
ans += m[s[i]];
}
}
return ans;
}
};
比较直观,只需要遍历所有位置,判断是要加还是减
2、Integer To Roman
class Solution {
public:
/**
* @param n: The integer
* @return: Roman representation
*/
string intToRoman(int n) {
// write your code here
vector<int> cases = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 ,1};
vector<string> symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string ans = "";
for(int i=0; i<cases.size(); i++){
int num = n/cases[i];
while(num--){
ans += symbols[i];
n -= cases[i];
}
}
return ans;
}
};
前提条件: n 在1~3999范围内
列出需要判断的特殊条件,再用循环比较高效和方便
题目列表:
https://www.lintcode.com/problem/integer-to-roman/description
https://www.lintcode.com/problem/roman-to-integer/description