012 - 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 - 1
II - 2
III - 3
IV - 4
V - 5
VI - 6
X - 10
L - 50
C - 100
D - 500
M - 1000

只有I X C可以放左边,而且放左边的数量级不可以越级,既只有C能放在D M左边,I X是不可以的


int lt1000(char *result, int num, int level, char n1, char n2, char n3)
{
	int k = 0;
	while (num >= level) {
		if (num >= 9 * level) {
			result[k++] = n1;
			result[k++] = n3;
			num -= 9 * level;
		} else if(num >= 5 * level) {
			result[k++] = n2;
			num -= 5 * level;
		} else if(num >= 4 * level) {
			result[k++] = n1;
			result[k++] = n2;
			num -= 4 * level;
		} else if(num >= level) {
			while (num >= level) {
				result[k++] = n1;
				num -= level;
			}
		}
	}
	return k;
}
char* intToRoman(int num) 
{
	int k = 0;
	static char out[16];
	while (num >= 1000) {
		out[k++] = 'M';
		num -= 1000;
	}
	if(num >= 100) k += lt1000(out + k, num % 1000, 100, 'C', 'D', 'M');
	if(num >= 10) k += lt1000(out + k, num % 100, 10, 'X', 'L', 'C');
	if(num >= 1) k += lt1000(out + k, num % 10, 1, 'I', 'V', 'X');
	out[k] = 0;
	return out;
}


你可能感兴趣的:(012 - Integer to Roman)