LeetCode_Integer to Roman

时间:2023-03-09 15:16:53
LeetCode_Integer to Roman
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 = ;
V = ;
X = ;
L = ;
C = ;
D = ;
M = ;
接下来应该是V开始的重复,但是上面要加一个横线,表示对应数字的1000倍。
而且对于某位上(以个位为例), – ,应该是:I,II,III,IV,V,VI,VII,VIII,IX
而,对于百位上, – ,应该是:C,CC,CCC,CD,D,DC,DCC,DCCC,CM
依此类推。
有一点比较有意思,那就是IV,正统的写法是IIII(写程序倒是容易些)。后来简写为IV,但是由于IV也是朱皮特神的名字,为了不让神的名字看起来像普通数字,这种简写遭到了很多人的抵制。
class Solution {
public:
void appendNumtoRoman(int digit, string &roman, char *symbol)
{
if(digit == ) return ;
if(digit <= ){
roman.append(digit, symbol[]);
}else if( digit == ){
roman.append(, symbol[]);
roman.append(, symbol[]);
}else if(digit == ){
roman.append(,symbol[]);
}else if(digit <= ){
roman.append(, symbol[]);
roman.append(digit - , symbol[]);
}else if(digit == ){
roman.append(, symbol[]);
roman.append(, symbol[]);
}
}
string intToRoman(int num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char symbol[]={'I','V','X','L','C','D','M','v','x'};
string roman = "";
int scale = ; for(int i = ; i >= ; i -= )
{
int digit = num /scale ;
appendNumtoRoman(digit, roman, symbol+i);
num = num% scale;
scale /= ;
} return roman ;
}
};

转自: http://blog.unieagle.net/2012/09/29/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Ainteger-to-roman/