首页 > 其他 > 详细

[Leetcode] 12 - Integer to Roman

时间:2015-01-12 16:34:01      阅读:247      评论:0      收藏:0      [点我收藏+]

原题链接:https://oj.leetcode.com/problems/integer-to-roman/


这题也是简单题,重点是要维持一个罗马数字的数组,然后每位计算时候,则数组往后扫2位,使用同样的计算方式得出当前位的罗马表示。


class Solution {
public:
    string intToRoman(int num) {
        char map[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        
        string res = "";
        int shift = 0;
        while (num) {
            int cur = num % 10;
            res = getStr(map + shift, cur) + res;
            num /= 10;
            shift += 2;
        }
        
        return res;
    }
    
    string getStr(char map[], int num) {
        string res = "";
        if (num > 0 && num < 4) {
            res.append(num, map[0]);
        } else if (num == 4) {
            res.append(1, map[0]);
            res.append(1, map[1]);
        } else if (num == 5) {
            res.append(1, map[1]);
        } else if (num > 5 && num < 9) {
            res.append(1, map[1]);
            res.append(num - 5, map[0]);
        } else if (num == 9) {
            res.append(1, map[0]);
            res.append(1, map[2]);
        }
        
        return res;
    }
};


[Leetcode] 12 - Integer to Roman

原文:http://blog.csdn.net/algorithmengine/article/details/42643341

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