每日一练之Roman to integer & integer to Roman【LeetCode No.12,13】

Integer to Roman
Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Subscribe to see which companies asked this question.
class Solution {
public:
  string intToRoman(int num) {
  string table[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 result;
    int count = 0;
    while(num > 0){
        int temp = num % 10;
        result = table[count][temp] + result;
        num /= 10;
        count++;
    }
    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.

Subscribe to see which companies asked this question

class Solution {
public:
    int romanToInt(string s) {
    unordered_map<char,int> T={
        {'I',1},{'V',5},{'X',10},{ 'L' , 50 },{ 'C' , 100 },{ 'D' , 500 },{ 'M' , 1000 }
    };
    int sum=T[s.back()];
    for(int i=s.length()-2;i>=0;--i)
    {
        if(T[s[i]]<T[s[i+1]]){sum-=T[s[i]];}
        else {sum+=T[s[i]];}
    }
    return sum;
    }
    
};

其实只要明白罗马数字和阿拉伯数字之间的转换关系,这两题还是不难的。

全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务