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

leetCode 12. Integer to Roman | 字符串 | Medium

时间:2016-08-19 22:36:11      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:字符串

12. Integer to Roman

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 intToRoman(int num) {
        string thousands[4] = {"","M","MM","MMM"};
        string hundreds[10] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        string tens[10] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        string units[10] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};

        string * hits[4] = {units,tens,hundreds,thousands};
        
        string result;
        int index = 0;
        while (num > 0)
        {
            result = hits[index][num % 10] + result;
            num = num / 10;
            index++;
        }
        
        return result;
    }
};

总结:

有时候题目没有那么难,不要自己搞的很复杂。问题简单化。简单化。。。


2016-08-19 15:16:29

本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1840309

leetCode 12. Integer to Roman | 字符串 | Medium

标签:字符串

原文地址:http://qiaopeng688.blog.51cto.com/3572484/1840309

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