#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.
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; }
相关文章推荐
- C++异常处理之terminate函数
- HDU-5272
- 推箱子小游戏源码
- QGraphicsView 框架学习(一)、图形元素的编辑
- OS X10.10 上kamailio的安装与配置
- POJ1195:Mobile phones(二维树状数组)
- Maven包装过程中跳过测试
- Android AIDL机制
- scrapy爬取豆瓣读书的图书信息
- 《人,绩效和职业道德》 读后感
- 《人,绩效和职业道德》读后感
- Windows下搭建Python环境
- UISlider
- 第十六周 项目一--平方根中的异常
- [解决问题]卸载掉猎豹无线wifi后出现了连不上网的情况
- code兴趣,是最好的老师;灯塔
- 周记 2015.6.21
- logminer获取数据字典文件时,需要设置UTL_FILE_DIR参数--logminer说明
- 第十三周项目3-立体类族共有的抽象类
- Android ADB的使用