首页 > 代码库 > Integer to Roman
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
普及一下罗马计数法
The base
I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000
If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.
So ‘IV‘ is ‘4‘ and ‘VI‘ is ‘6‘.
For the numbers above X, only the symbol right before it may be subtracted: so 99 is: XCIX (and not IC).
需要注意的是 4 = IV,9 = IX,40 = XL,90 = XC,400 = CD,900 = CM
方法很简单,设立基数及每个基数相对应的字符表示,然后依次取整及求余,算法比较简单,直接可以看代码:
1 class Solution { 2 public: 3 string intToRoman(int num) { 4 int base[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}; //base中的基数分别对应romanchar中的字符表示 5 char* romanchar[] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; 6 string ans; 7 for(int i=12; i>=0; --i) { //从最后基数开始 8 int cnt = num / base[i]; //有点类似模拟10进制,在i位上数字为几 9 num %= base[i]; //0~i-1位为余下的数10 while( cnt-- ) ans.append(romanchar[i]); //转换为romanchar11 }12 return ans;13 }14 };
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Integer to Roman
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。