leetcode012:Integer to Roman

来源:互联网 发布:东方证券金典版软件 编辑:程序博客网 时间:2024/05/18 00:18

问题描述

Given an integer, convert it to a roman numeral.

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

问题分析

阿拉伯数字转罗马数字,只要了解了规则(请看参考链接,解释的很清晰),代码还是很简单的。范围是1到3999,所以千位单独处理,而个十百位的处理逻辑完全一致:0123、4、5678、9四类情况。

代码

class Solution {public:    string intToRoman(int num) {        string ans;        int q = num / 1000;//千位        for (int i = 0; i < q; i++){            ans += 'M';        }        q = num / 100 % 10;//百位        if (q == 9) ans += "CM";        else if (q >= 5){            ans += 'D';            for (int i = 0; i < q - 5; i++)                ans += 'C';        }        else if (q == 4)            ans += "CD";        else        {            for (int i = 0; i < q; i++)                ans += 'C';        }        q = num / 10 % 10;//十位        if (q == 9) ans += "XC";        else if (q >= 5){            ans += 'L';            for (int i = 0; i < q - 5; i++)                ans += 'X';        }        else if (q == 4)            ans += "XL";        else        {            for (int i = 0; i < q; i++)                ans += 'X';        }        q = num % 10;//个位        if (q == 9) ans += "IX";        else if (q >= 5){            ans += 'V';            for (int i = 0; i < q - 5; i++)                ans += 'I';        }        else if (q == 4)            ans += "IV";        else        {            for (int i = 0; i < q; i++)                ans += 'I';        }        return ans;    }};
0 0
原创粉丝点击