将罗马数字字符串转换为阿拉伯整形数 Roman to Integer
来源:互联网 发布:上古卷轴5字体优化 编辑:程序博客网 时间:2024/06/06 00:48
题目源自于leetcode,和前一道是正好相反的计算。
另一道题在http://blog.csdn.net/ojshilu/article/details/12836795
思路:需要进行字符串的匹配,但是罗马数字并不是前/后缀编码,暂时没有想到好的方法。所以就枚举吧。
代码:
class Solution {public: int romanToInt(string s) { string cost[][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",""}};int value[] = {1,10,100,1000}; int result = 0; int n = s.length()-1; int idx = 0; while(n>=0) { if(n>=3 && s.substr(n-3,4) == cost[idx][8] ) { result += 8*value[idx]; n-=4; } else if(n>=2 && s.substr(n-2,3) == cost[idx][3] ) { result += 3*value[idx]; n-=3; } else if(n>=2 && s.substr(n-2,3) == cost[idx][7] ) { result += 7*value[idx]; n-=3; } else if(n>=1 && s.substr(n-1,2) == cost[idx][2] ) { result += 2*value[idx]; n-=2; } else if(n>=1 && s.substr(n-1,2) == cost[idx][4] ) { result += 4*value[idx]; n-=2; } else if(n>=1 && s.substr(n-1,2) == cost[idx][6] ) { result += 6*value[idx]; n-=2; } else if(n>=1 && s.substr(n-1,2) == cost[idx][9] ) { result += 9*value[idx]; n-=2; } else if( s.substr(n,1) == cost[idx][1] ) { result += 1*value[idx]; n--; } else if(s.substr(n,1) == cost[idx][5] ) { result += 5*value[idx]; n--; } idx++; } return result; }};
注意:string类型取子字符串的时候,怎么取?用substr函数。其第一个参数不可以越界、也不可以小于0,否则程序会崩。所以调用之前要做好判断。
- 将罗马数字字符串转换为阿拉伯整形数 Roman to Integer
- 将数字转换为罗马数字(Integer to Roman)
- Roman to Integer | Leetcode 罗马数字转换为整型数
- Integer to Roman (罗马数字转换)
- LeetCode 12. Integer to Roman(阿拉伯转罗马数字)
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- leetcode 12 Integer to Roman(整型数转换为罗马数字)
- 将阿拉伯数字转换成罗马数字 Integer to Roman
- leetcode 13 Roman to Integer(罗马数字转换为整数)
- Roman to Integer(罗马数字转换为整数)
- LeetCode-13-Roman to Integer(罗马数字转换为整型数字)
- Roman to Integer---罗马数字转换为十进制整数
- integer-to-roman and roman-to-integer罗马数字转换
- Integer to Roman (罗马数字转换) 【leetcode】
- Integer to Roman 整数转换成罗马数字
- Roman to Integer 罗马数字转换成整数
- LeetCode Roman to Integer(罗马数字转换)
- Roman to Integer:转换罗马数字到阿拉伯数字
- MPI string pack
- 图像运动去模糊(Motion Deblurring)代码
- iOS 发布应用程序到App Store
- exit()和_exit()的区别
- 从命令行启动应用程序
- 将罗马数字字符串转换为阿拉伯整形数 Roman to Integer
- 视频压缩cvCreateVideoWriter()的问题
- “iOS 推送通知”详解:从创建到设置到运行
- KindEditor 页面信息保存以后,打印卡死现象解决
- MFC文本编程,菜鸟篇,输入字符响应并显示在视类窗口中
- 数据块里的数据行不是等长的
- Log4J之Layout —— PatternLayout
- JSP与Facelets的区别
- springMVC controller forward