码迷,mamicode.com
首页 > 其他好文 > 详细

Integer to Roman

时间:2014-09-15 22:44:19      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   strong   

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]);    //转换为romanchar
11         }
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()); //截取已经去过的romanchar
12             }
13         }
14         return ans;
15     }
16 };

 

Integer to Roman

标签:style   blog   http   color   io   os   使用   ar   strong   

原文地址:http://www.cnblogs.com/bugfly/p/3973878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!