Roman chart: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

Integer to Roman

Given an integer, convert it to a roman numeral.

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

解析:只有数字为 9 和 4 时,取一个小数放在左边。(把数字为 9 和 4 时的罗马符号看作一个原子,避免取小数过程。)

 class Solution {
public:
string intToRoman(int num) {
string Roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int val[] = {, , , , , , , , , , , , };
string s;
for(int i = ; i < ; ++i){
while(num >= val[i]){
num -= val[i];
s += Roman[i];
}
}
return s;
}
};

 Roman to Integer

Given a roman numeral, convert it to an integer.

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

解析:1. 最直观想法,对字符串按罗马值从大到小比对。 (372 ms)

 bool inHead(string s1, string& s2)
{
if(s2 == "") return false;
int k = ;
auto it = s1.begin();
for(; it != s1.end(); ++it)
{
if(*it != s2[k++]) return false;
}
if(it == s1.end()){
s2.erase(, k);
return true;
}
} class Solution {
public:
int romanToInt(string s) {
string sigmal[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int a[] = {, , , , , , , , , , , , };
int num = ;
int k = ;
for(int i = ; i < ; ++i){
while(inHead(sigmal[i], s)){
num += a[i];
}
}
return num;
}
};

Code

2. 利用 hash 函数来做。(每个罗马字符范围都在 'A' - 'Z' 之间,对字符串从左到右扫描,若是出现逆序(按罗马值),则这个逆序对为一个值) (260ms)

 class Solution {
public:
int romanToInt(string s) {
char c[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
int v[] = {, , , , , , };
int hash[] = {};
for(int i = ; i < ; ++i){
hash[c[i]] = v[i];
}
int num = ;
int len = s.length();
for(int i = ; i < len; ++i){
if(i == len-){
num += hash[s[i]];
return num;
}
if(hash[s[i]] < hash[s[i+]]){
num += hash[s[i+]] - hash[s[i]];
++i;
}else num += hash[s[i]];
}
return num;
}
};

最新文章

  1. About me
  2. hdu 3839 Ancient Messages (dfs )
  3. [新手学Java]反射学习笔记
  4. 面试&amp;笔试常见题,你了解多少?
  5. Oracle之sql追踪
  6. Musical Theme - poj 1743(求最大不重叠重复子串)
  7. 高性能MySql进化论(九):查询优化器常用的优化方式
  8. Myeclipse程序调试快捷键及步骤详解
  9. jdk动态代理与cglib代理、spring aop代理实现原理
  10. ArcGIS 网络分析[4] 网络数据集深入浅出之连通性、网络数据集的属性及转弯要素
  11. 如何将div高度填满剩余高度
  12. Java集合:ConcurrentHashMap原理分析
  13. asp.net mvc 3.0 知识点整理 ----- (2).Controller中几种Action返回类型对比
  14. url查询参数解析
  15. codeforces4A
  16. Markdown基础教程
  17. 使用Java进行串口SerialPort通讯
  18. mui ajax 应用的跨域问题
  19. Python-内置函数3
  20. 怎么制作CHM格式电子书

热门文章

  1. Java - 简单的对象排序 - Comparator
  2. 使用 CSS 媒体查询创建响应式网站
  3. NSAssert的使用
  4. Unparsed aapt error(s)! Check the console for output解决方法
  5. PHP flush sleep 输出缓存控制详解
  6. linux命令:find
  7. java中Timer的使用
  8. 多线程、多进程、协程、缓存(memcache、redis)
  9. oop、try_except、单例模式
  10. leetcde37. Sudoku Solver