码迷,mamicode.com
首页 > 编程语言 > 详细

integer to roman leetcode c++实现

时间:2015-07-28 12:46:42      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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

integer to roman leetcode c++实现

标签:

原文地址:http://www.cnblogs.com/chess/p/4682143.html

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