Roman to Integer
来源:互联网 发布:王者荣耀芈月 知乎 编辑:程序博客网 时间:2024/06/14 05:50
题目
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
思路
首先,学习一下罗马数字,参考罗马数字罗马数字是最古老的数字表示方式,比阿拉伯数组早2000多年,起源于罗马
罗马数字有如下符号:
基本字符IVXLCDM对应阿拉伯数字1510501005001000计数规则: 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4正常使用时,连续的数字重复不得超过三次在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)
其次,罗马数字转阿拉伯数字规则(仅限于3999以内):
从前向后遍历罗马数字,如果某个数等于或者小于前一个数,则加上该数。反之,减去前一个数的两倍然后加上该数;
代码如下:
#include <iostream>#include <vector>#include <string>using namespace std;int romanToInt(string s);void main(){string a="DCXXI",b="MCMCLID";int n=romanToInt(a),n1=romanToInt(b);cout<<n<<" "<<n1;}int romanToInt(string s){/*roman['I']=1; roman['V']=5; roman['X']=10; roman['L']=50; roman['C']=100; roman['D']=500; roman['M']=1000; */char *p=new char[s.size()]; strcpy(p,s.c_str());//将string型转为char型数组vector<int> array;array.resize(s.size());int n=0;for (int i=0;i<s.size();i++){switch (p[i]){case 'I':array[i]=1;break;case 'V':array[i]=5;break;case 'X':array[i]=10;break;case 'L':array[i]=50;break;case 'C':array[i]=100;break;case 'D':array[i]=500;break;case 'M':array[i]=1000;break;default:cout<<"error\n";}if (i==0){n+=array[i];}else{if (array[i]<=array[i-1]){n+=array[i];}else{n+=array[i]-2*array[i-1];}}}return n;}运行结果为:
0 0
- Integer to Roman & Roman to Integer
- Integer to Roman & 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
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- 直接插入排序
- iOS: 枚举类型 enum,NS_ENUM,NS_OPTIONS
- Eclipse中文字体大小修改
- ArcGIS中的三种查询
- 黑马程序员——Java高新技术(MyEclipse常用快捷键)
- Roman to Integer
- 发布和订阅PPS
- 十分钟搞清字符集和字符编码
- Android 帧动画使用简介
- C++ list vector 和 数组 的区别
- COPY MySQL数据库锁机制
- 关于界面不能预览的问题
- YUM源配置
- RFID理论基础知识要点(前三章)