首页 > 代码库 > 【leetcode刷题笔记】Roman to Integer
【leetcode刷题笔记】Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题解:转换的方法:从左往右扫描罗马字符,如果当前的字符对应的数字比上一个数字小,就直接加上这个数字;否则加上这个数字并且减去上一个数字的两倍,然后更新上一个数字。利用一个HashMap存放罗马字符和数字的对应。
罗马数字和阿拉伯数字的对应表格参见http://www.cnblogs.com/sunshineatnoon/p/3856057.html
例如罗马数字DCXIX:500+100+10+1+10-2 = 619
代码如下:
1 public class Solution { 2 public int romanToInt(String s) { 3 if(s == null || s.length() == 0) 4 return 0; 5 6 HashMap<Character, Integer> map= new HashMap<Character,Integer>(); 7 map.put(‘I‘, 1); 8 map.put(‘V‘, 5); 9 map.put(‘X‘, 10);10 map.put(‘L‘, 50);11 map.put(‘C‘, 100);12 map.put(‘D‘, 500);13 map.put(‘M‘, 1000);14 15 int length = s.length();16 int result = map.get(s.charAt(0));17 int last = result;18 19 for(int i = 1;i < length;i++){20 int temp = map.get(s.charAt(i));21 if(temp <= last)22 result += temp;23 else24 result = result + temp - 2*last;25 last = temp;26 }27 28 return result;29 }30 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。