leetcode之路012 Integer to Roman
2015-07-28 20:56
302 查看
题目大意:将整数转化为罗马形式表示,输入为1-3999。对照表:
思路:
1、用map记录对照表,对输入字符进行查找对应值。
2、依次处理每一位,从最低位开始。对于每一位j,分5种情况,j=9,5<j<9,j=5,j=4,0<j<4,每一个处理是独立的,判断后添加相应字符到结果字符串resu中即可。
下面是ac的代码,时间为56ms:
下面是改进的代码,减少了运算,运行为52ms,如下:
讨论区比较简单的实现都是基于制定规则,用表来表示各种情况,进行查找得到值,如下:
基本字符 | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
1、用map记录对照表,对输入字符进行查找对应值。
2、依次处理每一位,从最低位开始。对于每一位j,分5种情况,j=9,5<j<9,j=5,j=4,0<j<4,每一个处理是独立的,判断后添加相应字符到结果字符串resu中即可。
下面是ac的代码,时间为56ms:
class Solution { public: string intToRoman(int num) { string resu; int i=10,j,k; int te1,te2; unordered_map<int,char> map; map[1]='I';map[5]='V';map[10]='X';map[50]='L'; map[100]='C';map[500]='D';map[1000]='M'; while(num*10>=i) { j=(num%i)/(i/10); if(j==9) { te1=1;te2=10; resu.push_back(map[te2*i/10]); resu.push_back(map[te1*i/10]); } else if(j>5) { te1=5;te2=1; for(k=0;k<j-5;++k) resu.push_back(map[te2*i/10]); resu.push_back(map[te1*i/10]); } else if(j==5) resu.push_back(map[5*i/10]); else if(j==4) { resu.push_back(map[5*i/10]); resu.push_back(map[1*i/10]); } else if(j>0) { for(k=0;k<j;++k) resu.push_back(map[1*i/10]); } i*=10; } reverse(resu.begin(),resu.end()); return resu; } };
下面是改进的代码,减少了运算,运行为52ms,如下:
class Solution { public: string intToRoman(int num) { string resu; int i=1,j,k; unordered_map<int,char> map; map[1]='I';map[5]='V';map[10]='X';map[50]='L'; map[100]='C';map[500]='D';map[1000]='M'; while(num) { j=num%10; if(j>5&&j<9) { for(k=0;k<j-5;++k) resu.push_back(map[1*i]); resu.push_back(map[5*i]); } else if(j>0&&j<4) { for(k=0;k<j;++k) resu.push_back(map[1*i]); } else if(j==9) { resu.push_back(map[10*i]); resu.push_back(map[1*i]); } else if(j==5) resu.push_back(map[5*i]); else if(j==4) { resu.push_back(map[5*i]); resu.push_back(map[1*i]); } i*=10; num=num/10; } reverse(resu.begin(),resu.end()); return resu; } };
讨论区比较简单的实现都是基于制定规则,用表来表示各种情况,进行查找得到值,如下:
string intToRoman(int num) { string table[4][10] = {{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, {"", "M", "MM", "MMM"} }; string result; int count = 0; while(num > 0){ int temp = num % 10; result = table[count][temp] + result; num /= 10; count++; } return result; }
相关文章推荐
- LeetCode_112 Path Sum
- bonecp使用数据源
- 王家林亲授《DT大数据梦工厂》大数据实战视频 Scala 深入浅出实战经典 - 第71讲
- Objective-C中的加号与减号
- HTML入门
- Android基础UI之创建新视图
- iOS新特性页面制作
- Cocos2d-JS项目之二:cocostudio基础控件的使用
- iOS前期OC训练OC_08,09内存管理
- tinyxml 使用说明http://blog.csdn.net/zww0815/article/details/8083550
- oozie 客户端常用命令
- 快速排序中运用插入排序算法
- 《机器学习实战》之K-均值聚类算法的python实现
- 异步调用webservice方法的时候传的参数只能用大写而不能用小写
- IOS开发—NSTimer
- IOS中NSUserDefaults的用法(轻量级本地数据存储)
- 【解决】Visual Studio Code无法检测到已安装的Git
- Java_Web三大框架之Hibernate配置文件(二)
- HDU 5316 Magician
- HDOJ 5325 Crazy Bobo 树形DP