13. Roman to Integer
来源:互联网 发布:淘宝生产许可证怎么办 编辑:程序博客网 时间:2024/05/16 18:36
要求写一个子程序实现输入一串罗马数字返回它代表的阿拉伯数字。实现思路是:使用一个map来将字母和数字联系起来,通过字母索引可以找到对应的数字,然后根据罗马数字的表示形式,从字符串后向前扫描如果前面的小于后面的则和减去前面的,否则加上前面的。
代码如下:
#include<iostream>#include<string>#include<map>class Solution {public: int romanToInt(string s) { map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};int sum = roman[s.back()];for (int i = s.length() - 2; i >= 0; i--) {if (roman[s[i]] < roman[s[i + 1]]) {sum -= roman[s[i]];} else {sum += roman[s[i]];}}return sum; }};
阅读全文
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
- 随笔之框架原理
- Linux前台、后台、挂起、退出、查看命令汇总
- CSS知识点整理
- 练习一(第二周)
- memmove函数与memcpy函数的模拟实现
- 13. Roman to Integer
- 实验7 寻址方式在结构化数据访问总的应用
- win10系统安装教程
- 坑爹的天空穹
- python调用PHP
- .jar文件打开方式没有Java(TM) Platform SE binary怎么办?
- 面试
- 深入java虚拟机
- 求和最接近整个序列和的一半的子序列,是个标准的子序列问题,不过不知道O(N^2)是不是最优的