[LeetCode] Integer to Roman
LeetCode to Integer
2023-09-11 14:17:25 时间
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字是由字符I,V,X,L,C,D,M等等表示的,其中
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
接下来应该是V开始的重复,但是上面要加一个横线,表示对应数字的1000倍。
个位应该是:I,II,III,IV,V,VI,VII,VIII,IX
十位应该是:X,XX,XXX,XL,L,LX,LXX,LXXX,XC
百位应该是:C,CC,CCC,CD,D,DC,DCC,DCCC,CM
千位就是: M,MM,MMM
从高位到地位取值,然后把字符串拼凑起来即可。
string romans[4][10] = { {"","I", "II","III","IV","V","VI","VII","VIII","IX" }, {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}, {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}, {"","M","MM","MMM"} }; class Solution { public: string digitToRoman(int digit, int pow) { return romans[pow][digit]; } string intToRoman(int num) { int base = 1000; int digit = 0; int pow = 4 - 1; string result; while(num) { digit = num/base; result += digitToRoman(digit, pow); num = num%base; base /= 10; pow --; } return result; } };
相关文章
- Leetcode 之Binary Tree Postorder Traversal(44)
- [systemd]How To Use Systemctl to Manage Systemd Services and Units
- Java实现 LeetCode 522 最长特殊序列 II(查找最长的非子序列的长度)
- Java实现 LeetCode 412 Fizz Buzz
- Java实现 LeetCode 387 字符串中的第一个唯一字符
- Java实现 LeetCode 199 二叉树的右视图
- Java实现 LeetCode 25 K个一组翻转链表
- LeetCode(38): 报数
- [LeetCode] Best Time to Buy and Sell Stock
- [LeetCode] Fraction to Recurring Decimal
- 123. 买卖股票的最佳时机 III ——【Leetcode每日一题】
- Leetcode 836. 矩形重叠
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)
- Leetcode - Best Time to Buy and Sell Stock
- LeetCode: Sum Root to Leaf Numbers [129]
- PAT 1033. To Fill or Not to Fill (贪心)
- PAT 1033 To Fill or Not to Fill[dp]
- leetcode 121. Best Time to Buy and Sell Stock
- leetcode 108. Convert Sorted Array to Binary Search Tree
- leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 13. Roman to Integer
- 【Mac系统】Vscode使用LeetCode插件报错‘leetcode.toggleLeetCodeCn‘ not found
- LeetCode 283. 移动零
- 【LeetCode】124.二叉树中的最大路径和
- 【leetcode】leetcode3 无重复字符的最长子串