# Roman to Integer

3999范围内的罗马数字不会用到加上划线的字母

class Solution {
public:
int romanToInt(string s) {
int map[26];
map['I'-'A'] = 1; map['V'-'A'] = 5; map['X'-'A'] = 10; map['L'-'A'] = 50;
map['C'-'A'] = 100; map['D'-'A'] = 500; map['M'-'A'] = 1000;
int res = 0, n = s.size();
s.push_back(s[n-1]);
for(int i = 0; i < n; i++)
{
if(map[s[i]-'A'] >= map[s[i+1]-'A'])
res += map[s[i]-'A'];
else res -= map[s[i]-'A'];
}
return res;
}
};

class Solution {
public:
int romanToInt(string s) {
int map[26];
map['I'-'A'] = 1; map['V'-'A'] = 5; map['X'-'A'] = 10; map['L'-'A'] = 50;
map['C'-'A'] = 100; map['D'-'A'] = 500; map['M'-'A'] = 1000;
int res = 0, n = s.size();
s.push_back(s[n-1]);
for(int i = 0; i < n; i++)
{
if(map[s[i]-'A'] >= map[s[i+1]-'A'])
res += map[s[i]-'A'];
else res -= map[s[i]-'A'];
}
return res;
}
};

# Integer to Roman

class Solution {
public:
string intToRoman(int num) {
string roman[4][10] = {
{"", "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"}
};

string ret = "";
int digit = 0;
while (num != 0) {
int remain = num % 10;
ret = roman[digit][remain] + ret;
digit++;
num /= 10;
}

return ret;
}
};

，理解了规则之后就可以这要写了。

class Solution {
public:
string intToRoman(int num) {
string str;
string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};
for(int i=0;num!=0;++i)
{
while(num>=value[i])
{
num-=value[i];
str+=symbol[i];
}
}
return str;
}
};

举报原因： 您举报文章：LeetCode之Roman & Integer 的转换（简单题） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)