13. Roman to Integer
来源:互联网 发布:公共场所网络上报 编辑:程序博客网 时间:2024/05/17 01:58
Problems:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Example:
Ⅶ,7
XCIII 93
题目大意是把罗马数字转换成阿拉伯数字。(吐槽一下题目应该给一些罗马数字的表示和表示方法,不过没关系,百度一下就出来了)。
基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
组数规则:
1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
3、V 和X 左边的小数字只能用Ⅰ。
4、L 和C 左边的小数字只能用X。
5、D 和M 左边的小数字只能用C。
Code:
class Solution {public: int romanToInt(string s) { int num = findInt(s[s.length() - 1]); int temp1, temp2; for (int i = s.length() - 2; i >= 0; i--) { temp1 = findInt(s[i]); temp2 = findInt(s[i + 1]); if (temp1 >= temp2) { num = num + temp1; } else { num = num - temp1; } } return num; } int findInt(char c) { if (c == 'I') { return 1; } if (c == 'V') { return 5; } if (c == 'X') { return 10; } if (c == 'L') { return 50; } if (c == 'C') { return 100; } if (c == 'D') { return 500; } if (c == 'M') { return 1000; } }};
做完AC了才发现,写得太复杂了,有点久没写C++,把STL的东西都忘记了,这道题可以用map来实行配对,就可以省去了很多if。
阅读全文
0 0
- 13. Roman to Integer
- 13.Roman to Integer
- 13. Roman to Integer
- 13.Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 由intern深入String的内存模型
- 自己动手写操作系统(六)
- timequest静态时序分析学习笔记——命令约束
- CSS——div & span
- mybatis-3-mapper.dtd
- 13. Roman to Integer
- timequest静态时序分析学习笔记——工具使用
- Unity_JsonUtility的局限性_086
- 卷积神经网络学习笔记(一):CNN概况
- (1)数据挖掘算法之C4.5
- jni platform so动态库不全的处理办法
- 排序-3-插入
- Io流和操作总结
- js中的get和set方法(demo说明)