题目 Given an integer, convert it to a roman numeral.
【Leetcode|12. Integer to Roman】Input is guaranteed to be within the range from 1 to 3999.
思路
题目思路很简单粗暴,因为整数不超过3999,那么根据罗马数字与整数间的转换关系,枚举个、十、百、千位上的罗马数字即可,如下图所示:
文章图片
代码
class Solution {
public:
string intToRoman(int num) {
string M[] = {"", "M", "MM", "MMM"};
//千
string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
//百
string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
//十
string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
//个
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
};
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- Python|Python Leetcode(665.非递减数列)