LeetCode上Roman to Integer的C++代码
来源:互联网 发布:影楼设计软件 编辑:程序博客网 时间:2024/06/08 09:39
首先我们需要了解罗马数字的表示方法,才能够设计罗马数字转化为整数的算法。罗马数字介绍可以详见百度百科或者维基百科等等。
可以简化如下
IVXLCDM1510501005001000根据罗马数字表示规则,我们可以初始化一个couter,然后一遍遍历,得出答案
代码如下
class Solution {public: int romanToInt(string s) {int sSize = s.size();int couter = 0;int i;string temp;for(i = 0;i < sSize;i ++){ if(s.substr(i,1) == "I"){ if(s.substr(i+1, 1) == "I" || (i+1) == sSize) couter ++; else couter --; } else if(s.substr(i, 1) == "V") couter += 5; else if(s.substr(i, 1) == "X"){ if(s.substr(i+1, 1) == "L" || s.substr(i+1, 1) == "C") couter -= 10; else couter += 10; } else if(s.substr(i, 1) == "L") couter += 50; else if(s.substr(i, 1) == "C"){if(s.substr(i+1,1) == "D" || s.substr(i+1,1) == "M")couter -= 100;elsecouter += 100; } else if(s.substr(i, 1) == "D") couter += 500; else if(s.substr(i, 1) == "M") couter += 1000;}return couter; }};
本来想用swich case语句,这样思想是相同的,代码量可以少一点。但在C++里面,switch语句,后面不能用string类型的变量,但可以通过hash表来解决,我就比较暴力的把switch写成了if else。
0 0
- LeetCode上Roman to Integer的C++代码
- [C++]LeetCode: 16 Roman to Integer
- [C++]LeetCode: 85 Integer to Roman
- C实现 LeetCode->Integer to Roman
- C实现 LeetCode->Roman to Integer
- 【leetcode c++】13 Roman to Integer
- [leetcode-13]Roman to Integer(C)
- [leetcode]Roman to Integer C语言
- Leetcode c语言-Integer to Roman
- Leetcode c语言-Roman to Integer
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- BC范式介绍
- 密码学综述
- 测鬼记(上)——报到(二)
- JDK、JRE、JVM三者的区别
- Linux系统与Windows系统中的回车与换行问题
- LeetCode上Roman to Integer的C++代码
- Java的优点
- HDU 1789 Doing Homework again
- Pandas数值计算与排序
- 浅谈BitMap
- 大数据的解决方案--------批量读取和延迟修改
- C/C++计算一重定积分和二重定积分(纯暴力算法实现)
- 中国计算机学会CCF推荐国际学术会议和期刊目录
- 谷哥的小弟学后台(36)——MyBatis的原始Dao开发方式