首页 > 其他 > 详细

【LeetCode从零单刷】Integer to Roman

时间:2015-05-13 12:57:20      阅读:128      评论:0      收藏:0      [点我收藏+]

题目:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!