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

【LeetCode从零单刷】Integer to Roman

时间:2015-05-13 13:00:05      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

题目:

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

解答:

慢慢模拟也可以。应该不会错。这里介绍一种“查表+ 拼接字符串”的方法。

class Solution {
public:
    string thousand[4] = {"", "M", "MM", "MMM"};
    string hundred[10] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    string tens[10] =    {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    string ones[10] =    {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    
    string intToRoman(int num) {
        string ans;
        ans += thousand[(int)(num / 1000) % 10];
        ans += hundred[(int)(num / 100) % 10];
        ans += tens[(int)(num / 10) % 10];
        ans += ones[num % 10];
        
        return ans;
    }
};


【LeetCode从零单刷】Integer to Roman

标签:c++   leetcode   

原文地址:http://blog.csdn.net/ironyoung/article/details/45690301

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