zoukankan      html  css  js  c++  java
  • Roman Number & Integer

    Problem I: Roman to Integer

    Given a roman numeral, convert it to an integer.

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

    解决思路

    1. 将字符和整数存入map中;

    2. 从后往前扫描,如果当前字符代表的值大于后一个字符的值,则用当前的值减去之前累计的值。e.g. "IV" -> 5 - 1 = 4

    程序

    public class Solution {
        public int romanToInt(String s) {
            if (s == null || s.length() == 0) {
    		    return 0;
    	    }
    	    
        	HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        	hm.put('I', 1);
        	hm.put('V', 5);
        	hm.put('X', 10);
        	hm.put('L', 50);
        	hm.put('C', 100);
        	hm.put('D', 500);
        	hm.put('M', 1000);
        	
        	int len = s.length();
        	int sum = hm.get(s.charAt(len - 1));
        	
        	for (int i = len - 2; i >= 0; i--) {
        	    char cur = s.charAt(i);
        	    char aft = s.charAt(i + 1);
        	    if (hm.get(cur) < hm.get(aft)) {
        	        sum -= hm.get(cur);
        	    } else {
        	        sum += hm.get(cur);
        	    }
        	}
        	
        	return sum;
        }
    }
    

    Problem II: Integer to Roman

    Given an integer, convert it to a roman numeral.

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

    解决思路

    1. 存一个数字到字符的映射表,数字从大到小,包含{1000, 900, 500, 400, 100, 90,
                50, 40, 10, 9, 5, 4, 1};

    2. 贪心原则,得到对应的字符串。

    程序

    public class Solution {
        public String intToRoman(int num) {
            String res = "";
            if (num <= 0) {
    			return res;
    		}
    		
    		int[] nums = {1000, 900, 500, 400, 100, 90, 
    			50, 40, 10, 9, 5, 4, 1};
    		String[] symbols = {"M", "CM", "D", "CD", "C", "XC",
    			"L", "XL", "X", "IX", "V", "IV", "I"};
    		
    		int i = 0;
    		
    		while (num > 0) {
    		    int j = num / nums[i];
    		    num -= j * nums[i];
    		    for ( ; j > 0; j--) {
    		        res += symbols[i];
    		    }
    		    ++i;
    		}
    		
    		return res;
        }
    }
    
  • 相关阅读:
    分享自Allen 《打开excel,word发送没反映OUTLOOK无法打开》
    AD域只禁用USB存储器而开放其他USB设备
    sql2000安装sp4补丁包教程_sql2000sp4
    为帮助保护您的安全,Internet Explorer已经阻止从此站点下载文件
    IExplore.exe应用程序错误解决方法
    单网卡双IP,同时上内外网
    关于
    七伤拳
    <转>在外企混的,一定要懂“外企潜台词”
    习惯
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4743216.html
Copyright © 2011-2022 走看看