LeetCode 012 Integer to Roman

12. Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
    string intToRoman(int num) {
    }
};
解题思路:
题目背景解析:
罗马数字共有 7 个,即 I(1) V(5) X(10) L(50) C(100) D(500) M(1000)
具体 roman 数字表示如下
I
V
X
L
C
D
M
1
5
10
50
100
500
1000
7 个字母分别代表不同的数字,用这 7 个字母排列组成可以组成所有的整数。
简单规则如下:
1 、相同的字母或者小的字母在大字母前就是相加。 III = 3 IV =6 ;
2 、大的字母在小的字母前面就是想减。 VI = 4 CM = 900;
  • 自己的解题思路
使用了辅助数组进行求解。当然这个辅助数组具有一定的特征,可以使用函数进行求解。然而,我们一般还是用空间来换时间。
这里使用了一个特征,就是 789 ——对应罗马数字的( 7 【百位】 +8 【十位】 +9 【个位】)。
  • 别人的解题思路
与我的类似,但是对于 1 4 5 9 分开讨论,可以借鉴一下。
学习收获:
  • 对于 stack, 没有 push_back(), 只有 push() 这个容易思维定势,需要注意。
其实,现在感觉 stack 还是很好用的。
  • Word 技巧
对于参考文献,经常出现中文拉的很长,就像“参       献”,然后英文往后排的现象,可以通过以下方法进行解决。
选中英文,右键 -> 段落 -> 中文版式 , 在“允许西文在单词中间换行”打勾。
graphic
附件 1 :程序
1 、自己的程序:
string   str [ 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" }
};
class Solution
{
     public :
     string intToRoman ( int num )
     {
         if ( num <= 0 || num > 3999 )   return string ();
         string res ;
         res . reserve ( 200 );
         stack < int > st ;
         int digits = 0 ;
         while ( num )
         {
             st . push ( num % 10 );
             num /= 10 ;
             ++ digits ;
         }
         while (! st . empty ())
         {
             int temp = st . top ();
             res += str [-- digits ][ temp ];
             st . pop ();
         }
         return res ;
     }
};
2 、别人的程序
class Solution
{
     public :
     string intToRoman ( int num )
     {
         string res ;
         string sym [] = { "M" , "CM" , "D" , "CD" , "C" , "XC" , "L" , "XL" , "X" , "IX" , "V" , "IV" , "I" };
         int val [] = { 1000 , 900 , 500 , 400 , 100 , 90 , 50 , 40 , 10 , 9 , 5 , 4 , 1 };
         for ( int i = 0 ; num != 0 ; i ++)
         {
             while ( num >= val [ i ])
             {
                 num -= val [ i ];
                 res += sym [ i ];
             }
         }
         return res ;
     }
};

附件2:扩展阅读:

参考资料:
  1. https://github.com/githubwoniu/learnprogram/blob/master/leetcode/13/leetcode_13.md
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值