leetCode 13.Roman to Integer (罗马数字转整形) 解题思路和方法
2015-07-05 20:54
363 查看
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:开始解此题的时候,立马想到上题的反转公式。话不多说,上代码。具体思路代码注释。
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:开始解此题的时候,立马想到上题的反转公式。话不多说,上代码。具体思路代码注释。
public class Solution { public int romanToInt(String s) { //将用到数据数组保存 int[] v1 = new int[]{1000,500,100,50,10,5,1}; String[] k1 = new String[]{"M", "D","C", "L","X","V","I"}; //双字符数组 int[] v2 = new int[]{900,400,90,40,9,4}; String[] k2 = new String[]{"CM","CD","XC", "XL", "IX", "IV"}; String temp = ""; int num = 0;//返回的数字 boolean isBreak = false;//双字符是否已经处理 while(s.length() > 0){ //字符串长度大于2 if(s.length() >= 2){ //取前两位字符 temp = s.substring(0,2); //与k2字符串比较 for(int i = 0; i < k2.length; i++){ //存在相等 if(k2[i].equals(temp)){ num += v2[i];//将数字加上 s = s.substring(2);//字符串更新 isBreak = true;//爽字符已处理,单字符不再处理 break; } } //如果双字符没有匹配,则截取单字符处理 if(!isBreak){ temp = s.charAt(0) + ""; for(int j = 0; j < k1.length; j++){ if(k1[j].equals(temp)){ num += v1[j]; s = s.substring(1); break; } } }else{ isBreak = false; } } //处理最后一个字符 else{ temp = s.charAt(0) + ""; for(int j = 0; j < k1.length; j++){ if(k1[j].equals(temp)){ num += v1[j]; s = s.substring(1); break; } } } //System.out.println(s); } return num; } }上述解法总体上思路比较清楚,但是相比下面的解法,整体代码上冗长,而且效率上也要低一些。
public class Solution { public int romanToInt(String s) { char[] ch = s.toCharArray();//转成字符数组 int num = 0; //字符数组遍历 for(int i = 0; i < ch.length - 1; i++){ //如果字符与之后的对应数值小,则本字符对应数值为减,否则为加 if(getRomanValue(ch[i]) < getRomanValue(ch[i+1])){ num -= getRomanValue(ch[i]); } else{ num += getRomanValue(ch[i]); } } //加上最后一个字符 num += getRomanValue(ch[ch.length - 1]); return num; } //第字符保存在方法中,返回相应数值 public static int getRomanValue(char c) { switch(c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } }
相关文章推荐
- SQL Server中的Merge关键字
- Hadoop运行原理详解
- mosquitto在Linux环境下的部署/安装/使用/测试
- STL之rb_tree的find函数
- DELL R710在阵列卡上做raid的图例
- mosquitto在Linux环境下的部署/安装/使用/测试
- Debian - 设置MYSQL开机启动
- 图形化界面知识点
- javascript 删除数组中所有指定的值
- 厦门海沧区磁盘只有1TB的解决方案
- 关于mac版eclipse的配置问题
- 简单dp HDU 2151
- debian终端默认编辑器
- hibernate它 11.many2many双向
- 反射知识总结
- javaSE学习笔记之反射
- HttpClient简单使用
- F题 hdu 1431 素数回文
- shell 调试
- SDK更新失败怎么办?最简单的办法!无需翻墙!