Leetcode: 13. Roman to Integer(Week2, Easy)
来源:互联网 发布:百度seo一本通pdf下载 编辑:程序博客网 时间:2024/05/17 02:10
注:本题总结了罗马数字的表示规律并设计算法实现罗马数字与阿拉伯数字的转换
Leetcode 13
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
题意:
- 给出一个罗马数字,请你编写一个程序将之转化为整数
思路:
罗马数字的基本字符: I、V、X、L、C、D、M,分别对应: 1、5、10、50、100、500、1000
罗马数字的规律:
I. 相同数字连写,所表示的数等于这些数字相加得到的数;
II. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数;
III. 小的数字,仅限于I、X、C,在大的数字的左边,所表示的数等于大数减小数得到的数
IV. 正常使用时连写的数字重复不得超过三次;
V. 在一个数的上面画一条横线,表示这个数增值1000倍
算法:
- 当第i+1的数小于第i的数,那么将他们加起来即可;
- 反之,减去两倍第i的数,然后加上第i+1的数。
代码如下:
/*2017/9/14 Roman to Integer思路:(1) 罗马数字的基本字符:I、V、X、L、C、D、M 分别对应: 1、5、10、50、100、500、1000(2) 罗马数字的规律:I. 相同数字连写,所表示的数等于这些数字相加得到的数;II. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数;III. 小的数字,仅限于I、X、C,在大的数字的左边,所表示的数等于大数减小数得到的数IV. 正常使用时连写的数字重复不得超过三次;V. 在一个数的上面画一条横线,表示这个数增值1000倍总而言之,本题的算法如下:当第i+1的数小于第i的数,那么将他们加起来即可;反之,减去两倍第i的数,然后加上第i+1的数。(3) 解题思路I. 定义一个map,用于存储罗马数字的基本字符,方便直接通过索引获取罗马数字基本字符对应的数字II. 算法核心部分,就是(2)V.中的实现*/class Solution {public: int romanToInt(string s) { /*将Roma数字的基本字符及其对应的阿拉伯数字存入到map容器中*/ map<char, int> Roman_elem; Roman_elem.insert(pair<char, int>('I', 1)); Roman_elem.insert(pair<char, int>('V', 5)); Roman_elem.insert(pair<char, int>('X', 10)); Roman_elem.insert(pair<char, int>('L', 50)); Roman_elem.insert(pair<char, int>('C', 100)); Roman_elem.insert(pair<char, int>('D', 500)); Roman_elem.insert(pair<char, int>('M', 1000)); /*算法的核心实现部分*/ int sum = Roman_elem[s[0]]; for (int i = 1; i < s.size(); ++i) { if (Roman_elem[s[i]] <= Roman_elem[s[i-1]]) { sum += Roman_elem[s[i]]; } else { sum = sum - 2*Roman_elem[s[i-1]] + Roman_elem[s[i]]; } } return sum; }};
阅读全文
0 0
- Leetcode: 13. Roman to Integer(Week2, Easy)
- (算法分析Week2)Roman to Integer[Easy]
- LeetCode 13. Roman to Integer -- Easy
- Leetcode 13. Roman to Integer (Easy) (cpp)
- Leetcode[Easy] -- Roman to Integer
- [Leetcode 13, Easy] Roman To Integer
- 【LeetCode】(13)Roman to Integer(Easy)
- LeetCode #13 - Roman to Integer - Easy
- Leetcode OJ 13 Roman to Integer [Easy]
- 13. Roman to Integer [easy] (Python)
- Easy-题目13:13. Roman to Integer
- LeetCode 13. Roman to Integer
- [LeetCode]13.Roman to Integer
- LeetCode --- 13. Roman to Integer
- [Leetcode] 13. Roman to Integer
- [leetcode] 13.Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 引发的血案
- android监听View加载完成
- Common(二)—— CMemQueue
- google-chrome 启动报错 nss_util.cc(627)] NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required
- React Native布局详细指南
- Leetcode: 13. Roman to Integer(Week2, Easy)
- 第4章 随机变量的数字特征
- Java学习之“凯撒密码”实例
- 垃圾收集器
- Android虚拟机多开检测
- mysql高级笔记(二)
- java包jar下载
- Jenkins入门系列之——02第二章 Jenkins安装与配置
- 饿了么项目(四)