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

[LeetCode] Integer to Roman

时间:2015-04-18 19:15:08      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Integer to Roman

Given an integer, convert it to a roman numeral.

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

解题思路:

数字转罗马字符。并不是非常复杂,罗马字符的表示如维基百科所述http://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97。由于数字不多,可以直接用枚举法表示。代码如下:

class Solution {
public:
    string intToRoman(int num) {
        string qianwei[]={"", "M", "MM", "MMM"};
        string baiwei[]={"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        string shiwei[]={"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        string gewei[] ={"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        
        string result="";
        
        result += qianwei[num/1000];    //千位
        
        num = num%1000;
        result += baiwei[num/100];      //百位
        
        num = num%100;
        result += shiwei[num/10];       //十位
        
        num = num%10;
        result += gewei[num];           //个位
        
        return result;
    }
};
网上看到另一个比较好的解法,比我的解法要简练,代码如下:

class Solution {
public:
    string intToRoman(int num) {
        string str;  
        string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};  
        int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1}; 
        for(int i=0;num!=0;++i)
        {
            while(num>=value[i])
            {
                num-=value[i];
                str+=symbol[i];
            }
        }
        return str;
    }
};



[LeetCode] Integer to Roman

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45115429

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