Integer to Roman

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 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4437915.html