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

Integer to Roman

时间:2015-04-18 20:25:54      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer, convert it to a roman numeral.

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

Analyse: Be cautious abou the expression of 4, 9 , 40, 90, 400, 900, they are IV, IX, XL, XC, CD, CM respectively. 

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string result;
 5         int times = num / 1000;
 6         if(times) result += numbers(M, times);
 7         int next = num % 1000;
 8         
 9         times = next / 500;
10         if(times) result += numbers(D, times);
11         next %= 500;
12         
13         times = next / 100;
14         if(times){
15             if(times == 4){
16                 if(result[result.length()-1] == D){
17                     result[result.length()-1] = C;
18                     result += M;
19                 }
20                 else result += "CD";
21             } 
22             else result += numbers(C, times);
23         } 
24         next %= 100;
25         
26         times = next / 50;
27         if(times) result += numbers(L, times);
28         next %= 50;
29         
30         times = next / 10;
31         if(times){
32             if(times == 4){
33                 if(result[result.length()-1] == L){
34                     result[result.length()-1] = X;
35                     result += C;
36                 }
37                 else result += "XL";
38             } 
39             else result += numbers(X, times);
40         } 
41         next %= 10;
42         
43         times = next / 5;
44         if(times) result += numbers(V, times);
45         next %= 5;
46         
47         times = next;
48         if(times){
49             if(times == 4){
50                 if(result[result.length()-1] == V){
51                     result[result.length()-1] = I;
52                     result += X;
53                 }
54                 else result += "IV";
55             } 
56             else result += numbers(I, times);
57         }
58         return result;
59     }
60     string numbers(char a, int times){
61         string result;
62         for(int i = 0; i < times; i++) result += a;
63         return result;
64     }
65 };

Integer to Roman

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4437915.html

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