Leetcode算法练习-easy篇-Roman to Integer
来源:互联网 发布:淘宝上的正品足球鞋店 编辑:程序博客网 时间:2024/06/08 19:23
题目简述:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
上图:
本题解法:
int retValue(char a){ if(a == 'M') return 1000; if(a == 'D') return 500; if(a == 'C') return 100; if(a == 'L') return 50; if(a == 'X') return 10; if(a == 'V') return 5; if(a == 'I') return 1;}int retPra(char a){ int ret = 0; if(a == 'M'){ ret = 7; goto End; } if(a == 'D'){ ret = 6; goto End; } if(a == 'C'){ ret = 5; goto End; } if(a == 'L'){ return 4; goto End; } if(a == 'X'){ ret = 3; goto End; } if(a == 'V'){ ret = 2; goto End; } if(a == 'I'){ ret = 1; goto End; }End : return ret;}class Solution {public: int romanToInt(string s) { int ret = 0; int s1 = 0, s2 = 0; for(int i = 0; i < s.length(); i++) { s1 = retPra(s[i]); s2 = retPra(s[i + 1]); if(s1 < s2) { ret += retValue(s[i + 1]) - retValue(s[i]); i++; } else ret += retValue(s[i]); } return ret; }};
然后就是再来看一下比较好的解法:
7msJAVA解法
public int romanToInt(String s) { int nums[]=new int[s.length()]; for(int i=0;i<s.length();i++){ switch (s.charAt(i)){ case 'M': nums[i]=1000; break; case 'D': nums[i]=500; break; case 'C': nums[i]=100; break; case 'L': nums[i]=50; break; case 'X' : nums[i]=10; break; case 'V': nums[i]=5; break; case 'I': nums[i]=1; break; } } int sum=0; for(int i=0;i<nums.length-1;i++){ if(nums[i]<nums[i+1]) sum-=nums[i]; else sum+=nums[i]; } return sum+nums[nums.length-1];}
比较高效的部分应该就是直接生成数组,并在数组中进行比较加减。
总结:本次采用C++实现,有意思的部分就是罗马数字的排列方式了,在下面附的是罗马数字的排列规则:(来自百度)
1-10就是: I II III IV V VI VII VIII IX X .
就是一个I代表一根手指表示1.
两个当然就是2.然后V表示的就是一只手也就是5.
然后放在大数左边的小数是减,如IV是4.
放在大数右边的小数是加如VI是6.
然后X表示两只手也就是10.剩下的就跟阿拉伯数字一样组合起来就好了.
20是XX 30是XXX 因为50是L,所以40是XL.然后60LX 70LXX 80LXXX 100是C.所以90是XC.然后十位和个位组合就好了.再附个表
数字排列表格
0 0
- Leetcode算法练习-easy篇-Roman to Integer
- Leetcode[Easy] -- Roman to Integer
- [Leetcode 13, Easy] Roman To Integer
- 【LeetCode】(13)Roman to Integer(Easy)
- LeetCode 13. Roman to Integer -- Easy
- Leetcode 13. Roman to Integer (Easy) (cpp)
- LeetCode #13 - Roman to Integer - Easy
- Leetcode OJ 13 Roman to Integer [Easy]
- Leetcode: 13. Roman to Integer(Week2, Easy)
- 【LeetCode算法练习(C++)】Integer to Roman
- 【LeetCode算法练习(C++)】Roman to Integer
- Leetcode算法练习-easy篇-Reverse Integer
- (算法分析Week2)Roman to Integer[Easy]
- LeetCode算法题之Roman to Integer
- 13. Roman to Integer leetcode算法笔记
- LeetCode算法题目: Integer to Roman
- [LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
- leetcode 013 Roman to Integer(难易度:Easy)
- <UE4>分析UObjectBase
- 直接选择排序
- C# WinForm开发系列之chart控件画折线图和柱形图并自定义鼠标移动到数据标记点显示提示信息
- 跟我学JavaScript--HTML DOM--节点,DOM对象方法,DOM对象属性
- linux 安装ntfs-3g
- Leetcode算法练习-easy篇-Roman to Integer
- 多表连接查询
- poj 2387(Dijkstra优先队列优化)
- 一个工厂模式的浅析
- java笔记---常用的API
- Common Subsequence 最长公共子序列
- 编码:隐匿在计算机软硬件背后的语言(4—6章)
- Win10+Google浏览器51.0.2704.103,日历被模态框遮挡
- struts1和struts2和springMVC的区别和介绍