Leetcode_12_Integer to Roman

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42744649


Given an integer, convert it to a roman numeral.

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

思路:

(1)题意为给定任意1—3999的整数,将其转化为罗马数字。

(2)该题和将罗马数字转化为整数类似,详见罗马数字转化为整数

(3)由于技术有限,本文还是先运用“暴力破解”的思想,对于1-10、10-100、100-1000、1000-3999分别进行讨论,由于比较简单,这里就不累赘了,详情见下方代码。

(4)希望本文对你有所帮助。

算法代码实现如下:

	/**
	 * @author liqq
	 */
    public String intToRoman(int num) {
    	Map<Integer, String> maps = new HashMap<Integer, String>();
    	maps.put(1,"I");
    	maps.put(2,"II");
    	maps.put(3,"III");
    	maps.put(4,"IV");
    	maps.put(5,"V");
    	maps.put(6,"VI");
    	maps.put(7,"VII");
    	maps.put(8,"VIII");
    	maps.put(9,"IX");
    	maps.put(10,"X");
    	maps.put(20,"XX");
    	maps.put(30,"XXX");
    	maps.put(40,"XL");
    	maps.put(50,"L");
    	maps.put(60,"LX");
    	maps.put(70,"LXX");
    	maps.put(80,"LXXX");
    	maps.put(90,"XC");
    	maps.put(100,"C");
    	maps.put(200,"CC");
    	maps.put(300,"CCC");
    	maps.put(400,"CD");
    	maps.put(500,"D");
    	maps.put(600,"DC");
    	maps.put(700,"DCC");
    	maps.put(800,"DCCC");
    	maps.put(900,"CM");
    	maps.put(1000,"M");
    	maps.put(2000,"MM");
    	maps.put(3000,"MMM");

    	StringBuffer buffer = new StringBuffer();
    	if(num<=10){
    		return maps.get(num);
    	}else if(num>10 && num<100){
    		int index = num/10;
    		buffer.append(maps.get(index*10));
    		if(num-index*10>0){
    			buffer.append(maps.get(num-index*10));
    		}
    		return buffer.toString();
    	}else if(num>=100 && num<1000){
    		int hun = num/100;
    		buffer.append(maps.get(hun*100));
    		int te = (num-hun*100)/10;
    		if(te>0){
    			buffer.append(maps.get(te*10));
    		}
    		if(num-hun*100-te*10>0){
        		buffer.append(maps.get(num-hun*100-te*10));
    		}
    		return buffer.toString();
    	}else if(num>=1000 &&num<=3999){
    		int th = num/1000;
    		buffer.append(maps.get(th*1000));
    		int hun = (num-th*1000)/100;
    		if(hun>0){
    			buffer.append(maps.get(hun*100));
    		}
    		int te = (num-th*1000-hun*100)/10;
    		if(te>0){
    			buffer.append(maps.get(te*10));
    		}
    		if(num-th*1000-hun*100-te*10>0){
        		buffer.append(maps.get(num-th*1000-hun*100-te*10));
    		}
    		return buffer.toString();
    	}
    	return buffer.toString();
    }
上一篇:CentOS-6.4无线上网命令行配置


下一篇:Linux源码编译安装程序