您的位置:首页 > 其它

#12 Integer to Roman

2015-06-21 21:20 232 查看
题目链接:https://leetcode.com/problems/integer-to-roman/

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

char* intToRoman(int num) {
int base = 1000;        //基数,1000、500、100、50……依次降低
int n = 2;              //在2和5之间迭代,用于基数一级一级降低
int i = 0;              //与基数相对应字符的下标
int j;
char ch[8] = "MDCLXVI";
char *ret = (char *)calloc(50, sizeof(char));
int k = 0;
while (num) {
while (num / base == 0) {       //找到最大基数及对应的字符等
base /= n;
n = 10 / n;
++i;
}
if (n == 2) {           //下一次基数下降2倍时,比如此时base = 1
if (num / base == 4) {      //余数为4,比如num = 4,输出时IX
ret[k++] = ch[i];
ret[k++] = ch[i - 1];
}
else                //余数是1、2、3时输出1、2、3个I
for (j = 0; j < num / base; ++j)
ret[k++] = ch[i];
num %= base;
}
else {              //下一个基数下降时5倍时,比如此时base = 5
if ((num + base / n) / base == 2) {     //(num = 9)余数(4)与2倍基数(2*base)差一个下层基数(base/n = 1),则输出IX
ret[k++] = ch[i + 1];
ret[k++] = ch[i - 1];
num = num + base / n - 2 * base;
}
else {              //否则输出V。   注意这里要分类的原因是9对IX,而不是VIV
ret[k++] = ch[i];
num %= base;
}
}
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: