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

【leetcode】Integer to Roman

时间:2015-01-03 18:28:19      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Integer to Roman

Given an integer, convert it to a roman numeral.

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

 
罗马数字的组数规则,有几条须注意掌握;(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。(2)不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。(3)V 和 X 左边的小数字只能用Ⅰ。(4)L 和 C 左边的小数字只能用×。(5)D 和 M 左 边的小数字只能用 C 
利用贪心算法
 
 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4        
 5         string result="";
 6         string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};    
 7         int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};
 8        
 9         int i=0;
10         while(num!=0)
11         {
12             while(num>=value[i])
13             {
14                 num=num-value[i];
15                 result+=symbol[i];
16             }
17             i++;
18         }
19         return result;
20     }
21 };

 

【leetcode】Integer to Roman

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4199716.html

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