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;
        }
    }
    
  • 相关阅读:
    安卓性能优化总结
    Splash广告界面
    安卓实现版本升级
    Kotlint集合简单总结
    Kotlin在处理GET和POST请求的数据问题
    udp 局域网群聊
    java 网络编程
    关于软件工程的课程建议
    结对编程--四则运算
    简单的结对代码练习
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4743216.html
Copyright © 2011-2022 走看看