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.

    public class Solution {
       /**
    	 * The algorithm is kind of greedy algorithm: cut the string into substrings such that
    	 * the length of each substring is as large as possible.<br> 
    	 * @param s -string, Roman expression of an integer
    	 * @return int
    	 * @author Averill Zheng
    	 * @version 2014-06-22
    	 * @since JDk 1.7
    	 */
    	public int romanToInt(String s) {
    		int sum = 0;
    		Map<String, Integer> roman2Int = new HashMap<String, Integer>();
    		int[] units = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};
            String[] romanNumeral = new String[]{"M","CM", "D", "CD", "C", "XC", "L",
            		"XL", "X", "IX", "V", "IV", "I"};
    		for(int i = 0; i < 13; ++i)
    			roman2Int.put(romanNumeral[i], units[i]);
    		int length = s.length();
    		int i = 0;
    		while(i < length){
    			if(i + 1 < length && (s.substring(i, i + 2).equals("CM") || s.substring(i, i + 2).equals("CD") ||
    					s.substring(i, i + 2).equals("XC") || s.substring(i, i + 2).equals("XL") ||
    					s.substring(i, i + 2).equals("IX") || s.substring(i, i + 2).equals("IV"))){
    				sum += roman2Int.get(s.substring(i, i + 2));
    				i += 2;
    			}			
    			else{
    				sum += roman2Int.get(s.substring(i, i + 1));
    				i += 1;
    			}
    		}
    		return sum; 
        }
    }
    

      

      

  • 相关阅读:
    RaisedButton
    Icon
    RichText
    GridView
    HTML常用标签
    HTML语法
    HTML简史
    17_继承
    16_Math
    16_ArrayList
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3803774.html
Copyright © 2011-2022 走看看