13 Roman to Integer
来源:互联网 发布:襄阳樊城区网络问政 编辑:程序博客网 时间:2024/05/16 06:10
其实还有点小意思,就String和Integer之间的数字转化, 把罗马数字String和Integer之间的转化规律用代码表示出来。。。
罗马数字规律:1,大方向:从左到右,所以用for loop + string.charAt(index) 来实现string的遍历;2,大多数情况,左大右小,是加法,所以大小判断要有数值,用HashMap来实现转化;3,如果是左小右大,那就是减法。就这三点,另外就是要知道几个罗马字符和代表的数字,面试遇到这题的可能不大,但是如果遇到了,一般会提供罗马数字的表。
之前代码:
public class Solution { public int romanToInt(String s) { if(s=="") return -1; Map<Character, Integer> map= new HashMap<Character, Integer>(); // 7 original pairs; map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int result=0; for(int i=0; i<s.length(); i++){ if(i==s.length()-1) result += map.get(s.charAt(i)); // 就是有一点,要判断和右边相邻位的数的大小,如果小就要减法,但是当index到了最高位了,就肯定是加了 + else{ if(map.get(s.charAt(i))<map.get(s.charAt(i+1))) result -= map.get(s.charAt(i)); // 减法 else result += map.get(s.charAt(i)); // 加法 } } return result; }}
今天的代码,5 mins 完成,still few typo: s.char(index) --> should be s.charAt(index) ,都是写太快了惹的祸,所以面试时,一定要检查一遍才跟面试官说,thats it, I am done with coding.
public class Solution { public int romanToInt(String s) { int len=s.length(); if(len==0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); // <Roman character, number> map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int result=0; for(int i=0; i<len-1; i++){ // 可以设置成 i<len,那就需要check i==len-1? 为了加速,我把这个写在外面 if(map.get(s.charAt(i))<map.get(s.charAt(i+1))) result-=map.get(s.charAt(i)); else result+=map.get(s.charAt(i)); } // 最后一个char写在for 外面是为了加快速度,特别当string很长,但是3999是最大值,所以也还好,哈哈 result+=map.get(s.charAt(len-1)); return result; }}
0 0
- 13、Roman to Integer
- 13、Roman to Integer
- 13Roman to Integer
- #13 Roman to Integer
- 13Roman 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
- Leetcode[12-13] Roman to Integer & Integer to Roman(Java)
- LeetCode_OJ【12】【13】Integer to Roman && Roman to Integer
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- leetcode-13:Roman to Integer
- leetcode 13 Roman to Integer
- UITableView 的横向滑动实现
- 170325 PyQt5-Label背景颜色和文本颜色的设置
- 书籍整理
- 实现MyBatis Mapper XML文件增量动态刷新,自动加载,热加载,热部署
- 我是一只忍者神龟.
- 13 Roman to Integer
- Hibernate 二级缓存 总结整理
- Android 输入法挤压屏幕解决方案
- Unity3D说明文档翻译-Mobile Device Input
- centos下tomcat+mysql的配置和项目部署
- 斐波那契数列及尾递归
- ubantu系统中Hadoop伪分布环境搭建与hbase配置
- CentOS 6.5搭建Tomcat+Mysql+JDK+FTP环境并部署项目
- ToolBar箭头的使用