Roman to Integer & Integer to Roman

题目:

Given a roman numeral, convert it to an integer.

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

解析:

这题没兴趣做,抄答案

http://blog.csdn.net/jellyyin/article/details/13165731

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int result=0;
 6         
 7         map<char,int> roman;
 8         roman['I']=1;
 9         roman['V']=5;
10         roman['X']=10;
11         roman['L']=50;
12         roman['C']=100;
13         roman['D']=500;
14         roman['M']=1000;
15         
16         for(int i=s.length()-1;i>=0;i--)
17         {
18             if(i==s.length()-1)
19             {
20                 result=roman[s[i]];
21                 continue;
22             }
23             if(roman[s[i]] >= roman[s[i+1]])
24                 result+=roman[s[i]];
25             else
26                 result-=roman[s[i]];
27         }
28         return result;
29     }
30 };

题目:

Given an integer, convert it to a roman numeral.

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

解析:

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         const int radix[] = {1000, 900, 500, 400, 100, 90,
 5             50, 40, 10, 9, 5, 4, 1};
 6         const string symbol[] = {"M", "CM", "D", "CD", "C", "XC",
 7             "L", "XL", "X", "IX", "V", "IV", "I"};
 8         string roman;
 9         for (size_t i = 0; num > 0; ++i) {
10             int count = num / radix[i];
11             num %= radix[i];
12             for (; count > 0; --count) roman += symbol[i];
13         }
14         return roman;
15     }
16 };
原文地址:https://www.cnblogs.com/raichen/p/4958169.html