Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
http://oj.leetcode.com/problems/integer-to-roman/
Solution:
First let's review the roman number: I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000
Basically it is to start from the MSB to LSB. There are 6 kinds of roman numbers and we use a for loop to scan it.
If the digit is less or equal to 3, it should be I~III, X~XXX, C~CCC or M~MMM.
If the digit is 4, it should be IV, XL or CD.
If the digit is 5, it should be V, L or D.
If the digit is from 6 to 8, it should be VI~VIII, LX~LXXX or DC~DCCC.
If the digit is 9, it should be like XI, CX or MC.
Since we check the int like 1000, 100, 10 and 1. So everytime we move 2 elements in the for loop.
https://github.com/starcroce/leetcode/blob/master/int_to_roman.cpp
// 360 ms for 3999 test cases
class Solution {
public:
string intToRoman(int num) {
char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
string res;
int scale = 1000;
// for loop to scan symbol[]
for(int i = 6; i >= 0; i -= 2) {
int digit = num / scale;
if(digit != 0) {
// append sth like I to III
if(digit <= 3) {
res.append(digit, symbol[i]);
}
// append sth like IV
if(digit == 4) {
res.append(1, symbol[i]);
res.append(1, symbol[i+1]);
}
// append sth like V
if(digit == 5) {
res.append(1, symbol[i+1]);
}
// append sth like VI to VIII
if(digit > 5 && digit <= 8) {
res.append(1, symbol[i+1]);
res.append(digit-5, symbol[i]);
}
// append sth like IX
if(digit == 9) {
res.append(1, symbol[i]);
res.append(1, symbol[i+2]);
}
}
num = num % scale;
scale /= 10;
}
return res;
}
};
本文介绍了一种将整数转换为罗马数字的算法实现,适用于1到3999范围内的整数。通过分析罗马数字的构成规律,采用循环遍历的方法逐位构建对应的罗马数字字符串。
455

被折叠的 条评论
为什么被折叠?



