Leetcode刷题记——12. Integer to Roman(阿拉伯数字转罗马数字)

一、题目叙述:

Given an integer, convert it to a roman numeral.

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

Subscribe to see which companies asked this question

二、解题思路:

这次是自己想的哈,吼吼吼~~~~其实只要知道罗马数字书写的规律,就可以写出来了,完全是找规律题,并没有什么不容易考虑到的限制条件。说说我的思路:

1.首先观察罗马数字的规律,每个罗马数字不会连续出现4个相同的。

2.从高位到低位,一位一位转换。首先把罗马数字和其对应的阿拉伯数字放入平行数组里,ro[]和roam[];

3.规律主要是这样的,比如百位数是x,当x在1到3之间,可以只用x个代表百的罗马数字‘C’ 表示;当x是4的时候,得用一个表示100的罗马数字‘C’和一个表示500的罗马数字‘D’表示;当x大于4小于9时,用一个表示500的罗马数字和x-5个表示100的罗马数字表示;当x为9时,就用一个表示100的罗马数字'C'和一个表示1000的罗马数字‘M’表示;

额。。。写的不够清楚哈,自行百度看规律~~~

三、源源源码:

public class Solution 
{
    public String intToRoman(int num) 
    {
    	String a = "";
    	int[] ro = {1000, 500, 100, 50, 10, 5, 1}; 
    	char[] roma = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};  
    	for (int i = 0; i < 7; i = i + 2)
    	{
    		int temp = num / ro[i];
    		if (temp < 4)
    			for (int j = 0; j < temp; j++)
    				a = a + roma[i] + "";
    		else if (temp == 4)
    			a = a + roma[i] + roma[i-1] + "";
    		else if (temp > 4 && temp < 9)
    		    {
    			 a = a + roma[i-1] + "";
    			 for (int j = 0; j < temp - 5; j++)
    				 a = a + roma[i] + "";
    		    }
    		else if (temp == 9)
    			a = a + roma[i] + roma[i-2] + "";
    		num = num - temp * ro[i];
    	}
    	return a;
    }
    
    public static void main(String[] args)
    {
    	int i = 90;
    	Solution a = new Solution();
    	System.out.println(a.intToRoman(i));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值