题目:Integer To Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
输入在1-3999范围内,参考百度百科对罗马数组的转化规则,可以从高位数推到低位数。
AC代码:
class Solution {
public:
string intToRoman(int num) {
int values [] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
string roman [] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
string result;
for(int i=0;i<13;i++){
while(num >= values[i]){
result += roman[i];
num -= values[i];
}
}
return result;
}
};
题目: Roman To Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
输入字符串表示的罗马数字,将其转换成int类型的阿拉伯数字。
根据转换规则:
int values [] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
string roman [] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
string roman [] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
可以知道遍历字符串的每一位时,可能会遇到要用两个字母表示一个阿拉伯数字的情况。
比如遇到字母‘C’,可能是‘CM’(900),‘CD’(400)或者只是‘C’(100)。所以要对其下一位进行判断,如果下一位对应的值大于C(M或者D),则加上900或者400,如果下一位对应值小于等于C,则加上100即可。
AC代码:
class Solution {
public:
int romanToInt(string s) {
int i=0 , result =0;
char cur,next;
while(i!=s.length()){
if(i!=s.length()-1 && romanValue(s[i+1]) > romanValue(s[i])){
result += (romanValue(s[i+1])-romanValue(s[i]));
i += 2;
}else{
result += romanValue(s[i]);
i++;
}
}
return result;
}
int romanValue(char c){
switch(c){
case 'M':return 1000;
case 'D':return 500;
case 'C':return 100;
case 'L':return 50;
case 'X':return 10;
case 'V':return 5;
case 'I':return 1;
}
}
};