首页 > 代码库 > Integer to Roman/Roman to Integer

Integer to Roman/Roman to Integer

 方法:注意罗马数字的分布即可

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; i<13; ++i)
        {
            while(num >= value[i])
            {
                str +=  symbol[i];
                num -= value[i];
            }
        }
        
        return str;
    }
};

Roman to Integer规则:

  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
  2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
  3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
class Solution {
public:
    int romanToInt(string s) {
        char symbol[]={M,D,C,L,X,V,I};    
        int value[]=    {1000, 500, 100, 50, 10, 5, 1}; 
        unordered_map<char, int>hashTable;
        for(int i=0; i<7; ++i)
            hashTable[symbol[i]] = value[i];
        
        int result = 0;
        for(int i=0; i<s.size(); ++i)
        {
            if(i>0 && hashTable[s[i]] > hashTable[s[i-1]])
            {
                result += hashTable[s[i]] - 2*hashTable[s[i-1]];
            }
            else
                result += hashTable[s[i]];
        }
            
        return result;
    }
};

 

Integer to Roman/Roman to Integer