《leetCode》:Roman to integer
来源:互联网 发布:软件项目验收申请报告 编辑:程序博客网 时间:2024/06/05 16:15
题目描述
Roman to integer
罗马数字介绍
基本字符 I V X L C D M相应的阿拉伯数字表示为 1 5 10 50 100 500 10001、相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;2、小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;3、小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;4、正常使用时、连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外);5、在一个数的上面画一条横线、表示这个数扩大 1000 倍。百度还给出了一些注意事项,如下:有几条须注意掌握:基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;V 和 X 左边的小数字只能用 Ⅰ;L 和 C 左边的小数字只能用X;D 和 M 左边的小数字只能用 C。
上面介绍的内容确实挺复杂的,但是在编程实现中只需要考虑以上三点内容
/*思路: 查看了下罗马数字的介绍,发现真的有点复杂也,然而看了下别人写的代码:发现只考虑到了如下的几点:1、相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;2、小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;3、小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;*/#include<stdio.h>#include<stdlib.h>#include<string.h>int roman2Num(char ch){ int res=0; switch(ch){ case 'I': res=1; break; case 'V': res=5; break; case 'X': res=10; break; case 'L': res=50; break; case 'C': res=100; break; case 'D': res=500; break; case 'M': res=1000; break; default: ; } return res;}int romanToInt(char* s) { if(s==NULL){ return 0; } int len=strlen(s); //将s从头开始遍历 int result=roman2Num(s[0]); for(int i=1;i<len;i++){ if(roman2Num(s[i-1])>=roman2Num(s[i])){//大数字在小数字前,应两者相加 result+=roman2Num(s[i]); } else{//小数字在大数字前,应该大数字减去见数字,但是之前我们加了一次小数字,因此要减小数字的两倍,例如:s="IV" result+=(roman2Num(s[i])-2*roman2Num(s[i-1])); } } return result; }int main(void){ char s[100]; while(gets(s)){ int result=romanToInt(s); printf("%d\n",result); }}
AC结果如下
0 0
- 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
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- 2015_11_01_水过去的10月
- Binary Search Tree
- S2SH+ajax+json-----jQuery中$.ajax解析xml、json格式数据
- 筛法欧拉函数
- java注解
- 《leetCode》:Roman to integer
- android---(音乐播放、在服务中使用 mediaPlay)
- java中static关键字
- 初涉网络,自己对服务器的一些基础理解
- Direct3D基础
- 数组。。。。
- 火柴排队
- 文章标题
- 韩咏梅:幸福只需要七分饱(转自新加坡联合早报)