Roman to Integer
:Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.题目大意是给你一个罗马数字让你转化为阿拉伯数字。不清楚罗马数
字请看维基百科的罗马数字的定义。这道题我是用map来做的,先将各个字母对应的
数字含义存到map里然后再通过遍历字符串来获得其数值。
代码:
class Solution {
public:
int romanToInt(string s) {
map<char, int> transition;
transition['I'] = 1;
transition['V'] = 5;
transition['X'] = 10;
transition['L'] = 50;
transition['C'] = 100;
transition['D'] = 500;
transition['M'] = 1000;
map<char, int>::iterator iter;
int result = 0;
char last = s[0];
char current = s[0];
for(int i = 0; i < s.length(); i++)
{
iter = transition.find(s[i]);
if(iter != transition.end())
{
current = s[i];
int lastValue = transition[last];
int currentValue = transition[current];
if(currentValue > lastValue)result = result + currentValue - 2 * lastValue;
else result += currentValue;
last = s[i];
}
}
return result;
}
};
因为计算罗马数字的数值时需要看当前字母与前一个字母的大小才能决定是加还是减,所以这里定义了一个lastValue和一个currentValue。
Integer to Roman
: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.这题刚好和上题相反,给你一个数让你转化为罗马数字。
这次用了一个转换表,根据这个字符串转换表来控制加入的字母。
代码:
class Solution {
public:
string transition;
string returnResult(int times, int n){
transition = "IVXLCDM";
string result;
if(times < 4)result.append(times, transition[n]);
else if(times == 4)result.append(1, transition[n]), result.append(1, transition[n + 1]);
else if(times == 5)result.append(1, transition[n + 1]);
else if(times >= 6 && times <= 8){
result.append(1, transition[n + 1]);
result.append(times - 5, transition[n]);
}
else {
result.append(1, transition[n]);
result.append(1, transition[n + 2]);
}
return result;
}
string intToRoman(int num) {
transition = "IVXLCDM";
string result = "";
int div = 1000;
int index = 6;
while(num != 0 && index >= 0){
int tmp = num / div;
if(tmp > 0)result += returnResult(tmp, index);
num %= div;
div /= 10;
index -= 2;
}
return result;
}
};