zoukankan      html  css  js  c++  java
  • [LeetCode 013] Roman to Integer

    Roman to Integer

    • 从后往前遍历字符串
    • 当前一个字符代表的数值比后一个小时,用最终结果减去这个数值
    • 否则,用最终结果加上这个数值

    Implementation

    public class Solution {
        public int romanToInt(String s) {
            if (s == null || s.length() == 0)
                return 0;
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            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 length = s.length();
    	    int result = map.get(s.charAt(length - 1));
    	    int current = result;
    	    for (int i = length - 2; i >= 0; i--) {
    	        int pre = map.get(s.charAt(i));
    	        result += (pre < current? -pre: pre);
    	        current = pre;
    	    }
    	    return result;
        }
    }
    
  • 相关阅读:
    第二章例2-9
    第二章例2-8
    第二章例2-7
    第二章例2-6
    第二章例2-5
    第二章例2-4
    第二章例2-3
    第二章例2-2
    第二章例2-1
    第一章例1-2
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5195000.html
Copyright © 2011-2022 走看看