49 : Integer to Roman
来源:互联网 发布:采石之战 知乎 编辑:程序博客网 时间:2024/05/19 02:04
题目:Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
在解题之前,最好要先了解一下罗马数字组合原理
罗马数字:
- 罗马数字采用 7 个罗马字母作数字,即
I(1),V(5),X(10),L(50),C(100),D(500),M(1000); - 相同的数字连写,所表示的数等于这些数字相加得到的数,如 III = 3,XX = 20, CC = 200, MM = 2000;
- 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 VIII = 8, XII = 12;为了简洁性,比如我们想要表达 80, 我们应该选择 LXXX, 而不是 8 个 X 连在一起;
- 小的数字(仅限于 I, X, C) 在大的数字的左边,所表示的数等于大数减小数得到的数。这样的组合共有 6 个,分别是 IV(4), IX(9), XL(40), XC(90), CD(400), CM(900),这 6 个 数字的表示不能应用上面的加法准则
若还不能理解,可以对照该网页https://zhidao.baidu.com/question/198335199.html 列出的罗马数字。
解题代码一如下,从整数的最低位即个位开始处理整数,代码比较繁琐,但理解起来比较容易
class Solution {public: string intToRoman(int num) { const char symbol[4][2] = {{'I', 'V'}, {'X', 'L'}, {'C', 'D'}, {'M'}}; string roman; for (int bit = 0; num; ++bit, num /= 10) { int tmp = num < 10 ? num : num % 10; string s; if (tmp == 9) { s.push_back(symbol[bit][0]); s.push_back(symbol[bit + 1][0]); } else if (5 <= tmp && tmp < 9) { s.push_back(symbol[bit][1]); for (int i = tmp - 5; i > 5; --i) s.push_back(symbol[bit][0]); } else if (tmp == 4) { s.push_back(symbol[bit][0]); s.push_back(symbol[bit][1]); } else { for (int i = tmp; i >= 1; --i) s.push_back(symbol[bit][0]); } roman = s + roman; } return roman; }};
解题代码二,从整数的最高位开始处理,代码很简洁,该代码参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目题目
class Solution {public: string intToRoman(int num) { const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string roman; for (int i = 0; num; ++i) { int counts = num / radix[i]; num %= radix[i]; for ( ; counts > 0; --counts) roman += symbol[i]; } return roman; }};
0 0
- 49 : Integer to Roman
- Integer to Roman & Roman to Integer
- Integer to Roman & Roman to Integer
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- windows环境下Android studio的安装教程
- Linux命令格式
- 一个简单的字符数组中字符的比较
- Spring 调试历险记
- 在FRDM-K64F开发板上搭建简易WEB服务器
- 49 : Integer to Roman
- 高精度计算
- Kotlin学习(三): 属性和字段
- 接口
- 169. Majority Element
- 1001A+BFormat
- MySQL事务简介
- Windows环境下搭建HBase源码开发环境
- hdu1411 校庆神秘建筑(海伦公式)