标签:style blog http color io os 使用 ar strong
Input is guaranteed to be within the range from 1 to 3999.
普及一下罗马计数法
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]); //转换为romanchar 11 } 12 return ans; 13 } 14 };
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
标签:style blog http color io os 使用 ar strong
原文地址:http://www.cnblogs.com/bugfly/p/3973878.html