zoukankan      html  css  js  c++  java
  • [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.

    ------------------------

    题是比较简单,但是解法中用了static block。

    public class Solution {
        
        private static Map<Character, Integer> map;
        static {
            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);
        }
    
        public int romanToInt(String s) {
            if(s == null || s.length() == 0)
                return 0;
            int res = 0;
            for (int i = 0; i < s.length() - 1; ++i){
                int cur = map.get(s.charAt(i));
                int next = map.get(s.charAt(i + 1));
                if(cur < next) {
                    res -= cur;
                } else {
                    res +=cur;
                }
            }
            res += map.get(s.charAt(s.length()-1));
            return res;
        }
    }

    ------------------------------

    Static block: http://stackoverflow.com/questions/2943556/static-block-in-java

    Notice: the order of execution is: static initializer, instance initializer, constructor

  • 相关阅读:
    2008年总结
    感触
    24105
    事情总喜欢蜂拥而至
    最后的稻草
    什么叫服务
    sigh,终于submit了
    在工作和生活的狭缝中生存着
    不应该,不应该
    ren 人 认 忍 韧 仁
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4823272.html
Copyright © 2011-2022 走看看