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

【LeetCode】12 - Integer to Roman

时间:2015-08-08 21:05:42      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer, convert it to a roman numeral.

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

Solution: 枚举,考虑每个字符以及每两个字符的组合

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {    //runtime:28ms
 4         string ret;
 5         //M<-->1000
 6         while(num >= 1000)
 7         {
 8             ret += M;
 9             num -= 1000;
10         }
11         //to here, num < 1000
12         //CM<-->900
13         if(num >= 900)
14         {
15             ret += "CM";
16             num -= 900;
17         }
18         //to here, num < 900
19         //D<-->500
20         if(num >= 500)
21         {
22             ret += D;
23             num -= 500;
24         }
25         //to here, num < 500
26         if(num >= 400)
27         {
28             ret += "CD";
29             num -= 400;
30         }
31         //to here, num < 400
32         //C<-->100
33         while(num >= 100)
34         {
35             ret += C;
36             num -= 100;
37         }
38         //to here, num < 100
39         //XC<-->90
40         if(num >= 90)
41         {
42             ret += "XC";
43             num -= 90;
44         }
45         //to here, num < 90
46         //L<-->50
47         if(num >= 50)
48         {
49             ret += L;
50             num -= 50;
51         }
52         //to here, num < 50
53         //XL<-->40
54         if(num >= 40)
55         {
56             ret += "XL";
57             num -= 40;
58         }
59         //to here, num < 40
60         //X<-->10
61         while(num >= 10)
62         {
63             ret += X;
64             num -= 10;
65         }
66         //to here, num < 10
67         //IX<-->9
68         if(num >= 9)
69         {
70             ret += "IX";
71             num -= 9;
72         }
73         //to here, num < 9
74         //V<-->5
75         if(num >= 5)
76         {
77             ret += V;
78             num -= 5;
79         }
80         //to here, num < 5
81         //IV<-->4
82         if(num >= 4)
83         {
84             ret += "IV";
85             num -= 4;
86         }
87         //to here, num < 4
88         //I<-->1
89         while(num >= 1)
90         {
91             ret += I;
92             num -= 1;
93         }
94         return ret;
95     }
96 };

 

【LeetCode】12 - Integer to Roman

标签:

原文地址:http://www.cnblogs.com/irun/p/4713789.html

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