棋子

导航

integer to roman leetcode c++实现

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 };

posted on 2015-07-28 10:44  鼬与轮回  阅读(172)  评论(0编辑  收藏  举报