zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    Given a roman numeral, convert it to an integer.
    Input is guaranteed to be within the range from 1 to 3999.

    思路:

    把关键数值对应起来,然后n-1位扫到第0位。

    package manipulation;
    
    import java.util.HashMap;
    
    public class RomanToInteger {
    
        public int romanToInt(String s) {
            int len = 0;
            if (s == null || (len = 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 res = map.get(s.charAt(len - 1));
            for (int i = len - 2; i >= 0; --i) {
                if (map.get(s.charAt(i + 1)) > map.get(s.charAt(i)))
                    res -= map.get(s.charAt(i));
                else
                    res += map.get(s.charAt(i));
            }
            
            return res;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            RomanToInteger r = new RomanToInteger();
            System.out.println(r.romanToInt("MCM"));
        }
    
    }
  • 相关阅读:
    请求参数的中文乱码问题
    MySql索引与优化
    Android 兼容包
    Mysql 主从(转)
    解决tomcat一闪而过(转)
    log4j
    支付相关
    通过maven添加quartz
    linux命令学习之:chmod
    Nginx特点及其配置
  • 原文地址:https://www.cnblogs.com/null00/p/5048262.html
Copyright © 2011-2022 走看看