13. Roman to Integer

题目:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

链接:https://leetcode.com/problems/roman-to-integer/

2/9/2017

主要问题在不熟悉Java,举例:

HashMap<char, integer> --> HashMap<Character, Integer>,

String.length(), 与array的length不同

String.charAt()

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
 4         dict.put('I', 1);
 5         dict.put('V', 5);
 6         dict.put('X', 10);
 7         dict.put('L', 50);
 8         dict.put('C', 100);
 9         dict.put('D', 500);
10         dict.put('M', 1000);
11         int prevValue = 0;
12         int result = 0;
13         int curValue = 0;
14 
15         for(int i = 0; i < s.length(); i++) {
16             curValue = dict.get(s.charAt(i));
17             if (prevValue != 0 && prevValue < curValue) {
18                 result = result + curValue - 2 * prevValue;
19             }else {
20                 result = result + curValue;
21             }
22             prevValue = curValue;
23         }
24         return result;
25     }
26 }

还是要熟悉语言啊

posted @ 2017-02-10 06:30  panini  阅读(151)  评论(0编辑  收藏  举报