Leetcode_12_Integer to Roman

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处: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();
    }


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值