Integer to Roman
罗马数字
1~9: {“I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”};
10~90: {“X”, “XX”, “XXX”, “XL”, “L”, “LX”, “LXX”, “LXXX”, “XC”};
100~900: {“C”, “CC”, “CCC”, “CD”, “D”, “DC”, “DCC”, “DCCC”, “CM”};
1000~3000: {“M”, “MM”, “MMM”}.
实现
class Solution {
public:
string intToRoman(int num) {
string Roman_Dict[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M", "MM", "MMM"};
int Roman_Int[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900,
1000, 2000, 3000
};
string result;
int dict_len = 30;
while(num > 0) {
if(num >= Roman_Int[dict_len]) {
result += Roman_Dict[dict_len];
num -= Roman_Int[dict_len];
}
dict_len--;
}
return result;
}
};
13. Roman to Integer
实现
法一:
class Solution {
public:
int romanToInt(string s) {
string Roman_Dict[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII",
"IX", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX",
"XC", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC",
"CM", "M", "MM", "MMM"};
int Roman_Int[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50,
60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700,
800, 900, 1000, 2000, 3000};
int result = 0;
while(s.length() >= 1) {
int tar = 0;
int i;
for(i = 30; i >= 0; i--) {
tar = Roman_Dict[i].size();
if(s.substr(0, tar) == Roman_Dict[i])
break;
}
result += Roman_Int[i];
s = s.erase(0, tar);
}
return result;
}
};
法二:
class Solution {
public:
int romanToInt(string s) {
if(s.length() == 0) return 0;
int len = s.length(), num = 0, add = 0, prev = 0;
for(int i = len-1; i >= 0; --i){
if(s[i] == 'I') add = 1;
else if(s[i] == 'V') add = 5;
else if(s[i] == 'X') add = 10;
else if(s[i] == 'L') add = 50;
else if(s[i] == 'C') add = 100;
else if(s[i] == 'D') add = 500;
else if(s[i] == 'M') add = 1000;
if(add >= prev) num += add;
else num -= add;
prev = add;
}