Given an integer, convert it to a roman numeral.

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

将整数用罗马数字表示。

思路分析:  

{"","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"}

    首先从输入的整数开始,(1)取其个位上的数值,判定后得到一个字符串(这个字符串也应该位于罗马数字的最右边,所以再用一个栈来解决)

               (2)然后将整数除以10(轮到十位上的数值了),再去执行(1)

代码如下:

    

 1 #include<stack>
 2 class Solution {
 3 public:
 4     string intToRoman(int num) {
 5         vector<vector<string>> data={
 6             {"","I","II","III","IV","V","VI","VII","VIII","IX"},
 7             {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
 8             {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
 9             {"","M","MM","MMM"}
10         };
11         stack<string> sta;
12         int i=0;
13         string res="",result="";
14         while(num!=0){
15             int remain=num%10;
16             res=data[i][remain];
17             sta.push(res);
18             ++i;
19             num/=10;
20         }
21         while(!sta.empty()){
22             result+=sta.top();
23             sta.pop();
24         }
25         return result;
26     }
27 };

相关文章:

  • 2021-11-24
  • 2021-12-28
  • 2021-11-22
  • 2022-03-01
  • 2022-02-19
  • 2021-12-29
  • 2021-12-29
  • 2021-09-17
猜你喜欢
  • 2021-12-31
  • 2021-06-06
  • 2022-02-15
  • 2021-07-08
  • 2022-12-23
  • 2021-05-22
  • 2022-02-12
相关资源
相似解决方案