leetcode012:Integer to Roman
2015-04-09 22:06
393 查看
问题描述
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; } };
相关文章推荐
- leetcode 012 Integer to Roman
- 【LeetCode-面试算法经典-Java实现】【012-Integer to Roman(数字转罗马字符)】
- 2017-09-09 LeetCode_012 Integer to Roman
- leetcode-012:Integer to Roman
- [LeetCode]-012-Integer to Roman
- leetcode解题方案--012--Integer to Roman
- LeetCode 012 Integer to Roman
- leetcode_c++: Integer to Roman(012)
- LeetCode 012 Integer to Roman
- 【JAVA、C++】LeetCode 012 Integer to Roman
- [LeetCode]题解(python):012-Integer to Roman
- LeetCode 012 Integer to Roman
- LeetCode 012 Integer to Roman
- Leetcode012 Integer to Roman
- leetcode-012-Integer to Roman
- LeetCode 012 Integer to Roman
- leetcode 012 —— Integer to Roman
- leetcode012 Integer to Roman
- [LeetCode]012-Integer to Roman
- LeetCode 012: Integer to Roman