Roman to Integer 的原题如下:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这里涉及roman数字的表示问题,用map表示对应的转换关系,然后从roman数字的最后一位向前逐位转换,转换过程中加上或者减去相应的数。class Solution {
public:
int romanToInt(string s) {
if(s.size() == 0)
return 0;
int sum = 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 i = s.size() - 1;
sum = m[s[i--]];
while(i >=0){
if(m[s[i + 1]] > m[s[i]])
sum -=m[s[i--]];
else
sum +=m[s[i--]];
}
return sum;
}
};
Integer to Roman 的原题如下:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
与上题相似,这里也是采用对应关系,分别用数组保存Roman数字和阿拉伯数字,利用数组下标连接其对应关系,将数字从最大到最小依次相减,同时转换其对应的roman数字。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.append(symbol[i]);
}
}
return str;
}
};
上述两题都是采用了映射的形式进行转换,既可以借助map,也可以借助数组。这种转换方法要注意掌握。另外,第二题也可以借助map实现。
string intToRoman(int num) {
string str;
map<int,string>mp;
mp[1000] = "M";
mp[900] = "CM";
mp[500] = "D";
mp[400] = "CD";
mp[100] = "C";
mp[90] = "XC";
mp[50] = "L";
mp[40] = "XL";
mp[10] = "X";
mp[9] = "IX";
mp[5] = "V";
mp[4] = "IV";
mp[1] = "I";
map<int,string>::iterator it = mp.end();
it--;
while(num != 0){
while(num >= it->first){
num -= it->first;
str +=it->second;
}
if(it != mp.begin())//防止迭代器越界
it--;
}
return str;
}