Leetcode ☞ 12. Integer to Roman ☆
2016-02-29 17:58
399 查看
12. Integer to Roman
My SubmissionsQuestion
Total Accepted: 57002 Total
Submissions: 151392 Difficulty: Medium
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
跟第13题Leetcode ☞ 13. Roman to Integer相反:http://blog.csdn.net/dr_unknown/article/details/50762420
我的AC(22ms,击败77%):
<span style="font-size:18px;">char* intToRoman(int num) {
char* ans = (char*)calloc(20, sizeof(char));
int index = 0;
while(num >= 1000){
ans[index++] = 'M';//M:1000
num -= 1000;
}
if (num >= 900){
ans[index++] = 'C';//C:100
ans[index++] = 'M';//M:1000
num -= 900;
}
if (num >= 500){
ans[index++] = 'D';//D:500
num -= 500;
}
if(num >= 400){
ans[index++] = 'C';//C:100
ans[index++] = 'D';//D:500
num -= 400;
}
while(num >= 100){
ans[index++] = 'C';//C:100
num -= 100;
}
if (num >= 90){
ans[index++] = 'X';//X:10
ans[index++] = 'C';//C:100
num -= 90;
}
if (num >= 50){
ans[index++] = 'L';//L:50
num -= 50;
}
if(num >= 40){
ans[index++] = 'X';//X:10
ans[index++] = 'L';//L:50
num -= 40;
}
while(num >= 10){
ans[index++] = 'X';//X:10
num -= 10;
}
if (num >= 9){
ans[index++] = 'I';//I:1
ans[index++] = 'X';//X:10
num -= 9;
}
if (num >= 5){
ans[index++] = 'V';//V:5
num -= 5;
}
if(num >= 4){
ans[index++] = 'I';//I:1
ans[index++] = 'V';//V:5
num -= 4;
}
while(num){
ans[index++] = 'I';
num--;
}
ans[index] = '\0';
return ans;
}</span>
分析:
1、4是5之前减一个1,8是5后面加三个1,9是10之前减一个1。知道这些就能知道罗马数字是如何组合的了。
2、此解法是很细的分情况。还有另外两种解法,时间一样:
C语言:https://leetcode.com/discuss/89381/three-simple-understanding-different-solutions-explained
相关文章推荐
- Node.js笔记(一)
- Elasticsearch基础教程
- 几何不变矩 Hu 矩
- Spring Data JPA教程:审计(一)
- Java中字符流的主要操作归纳
- 详解Paint的setShader(Shader shader)
- 课后作业1
- (27)odoo 中改变菜单动作的默认视图
- java 文件读取
- 安卓简易计算器
- (十二)状态模式
- Linux之IP配置
- 论年轻人买房的重要性
- bzoj:1500: [NOI2005]维修数列
- 深拷贝和浅拷贝的区别
- 身为品牌广告主,你需要的是的RTB还是PMP
- viewpager 滑动,缩放,子控件偏移引导页
- aix5.3下安装svn命令
- ACE_Reactor模式(handle_input的工作)V1.0
- 详解Android应用开发中Scroller类的屏幕滑动功能运用