首页 > 代码库 > Integer to Roman

Integer to Roman

Given an integer, convert it to a roman numeral.

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

 

普及一下罗马计数法

The base

I - 1

V - 5

X - 10

L - 50

C - 100

D - 500

M - 1000

If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.

So ‘IV‘ is ‘4‘ and ‘VI‘ is ‘6‘.

For the numbers above X, only the symbol right before it may be subtracted: so 99 is: XCIX (and not IC).

需要注意的是 4 = IV,9 = IX,40 = XL,90 = XC,400 = CD,900 = CM

方法很简单,设立基数及每个基数相对应的字符表示,然后依次取整及求余,算法比较简单,直接可以看代码:

 1 class Solution { 2 public: 3     string intToRoman(int num) { 4         int base[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};    //base中的基数分别对应romanchar中的字符表示 5         char* romanchar[] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; 6         string ans; 7         for(int i=12; i>=0; --i) {  //从最后基数开始 8             int cnt = num / base[i];    //有点类似模拟10进制,在i位上数字为几 9             num %= base[i]; //0~i-1位为余下的数10             while( cnt-- ) ans.append(romanchar[i]);    //转换为romanchar11         }12         return ans;13     }14 };

 

Roman to Integer

 

Given a roman numeral, convert it to an integer.

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

 

罗马数字转为10进制数字,与上题使用同样地算法,建立映射表,不断从高位来匹配romanchar,然后加上相应的基数

 1 class Solution { 2 public: 3     int romanToInt(string s) { 4         int base[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};    //base中的基数分别对应romanchar中的字符表示 5         char* romanchar[] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; 6         int ans = 0; 7         for(int i=12; i>=0 && !s.empty(); --i) { 8             string str(romanchar[i]);   //取i位上相应的romanchar 9             while( s.substr(0, str.length()) == str ) { //若一直都相等,那么就一直取10                 ans += base[i];11                 s = s.substr(str.length()); //截取已经去过的romanchar12             }13         }14         return ans;15     }16 };

 

Integer to Roman