Integer to Roman

Given an integer, convert it to a roman numeral.

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

Have you been asked this question in an interview?

罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)

  • 重复数次:一个罗马数字重复几次,就表示这个数的几倍。
  • 右加左减:
    • 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
    • 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
    • 左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
    • 但是,左减时不可跨越一个位数。比如,99不可以用IC(100 - 1)表示,而是用XCIX([100 - 10] + [10 - 1])表示。(等同于阿拉伯数字每位数字分别表示。)
    • 左减数字必须为一位,比如8写成VIII,而非IIX。
    • 右加数字不可连续超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)


roman to integer 和 integer to Roman 是用了完全不同的方式。 这里要分别考虑 9,90,900,4,40,400,5,50,500 这几种情况。
另外, 例如 19 是 XIX, 9用IX 表示。 而且不需要写成 IXX. 由于这一点觉得 如果是9的话,不光要写成 IX, 还要放在最前面,导致浪费了一些时间。
罗马数字 本着还是从高位到底位以此表示。
public class Solution {
    public String intToRoman(int num) {
        if (num > 3999 || num < 1) {
            return null;
        }
        char[] roman = {'I','V','X','L','C','D','M'};
        int scale = 1000;
        int count = 0;
        StringBuilder res = new StringBuilder();
        for (int i = 6; i >= 0; i -= 2) {
            count = num/scale;
            if (count == 0) {
                //不要漏掉对num 和 scale 的处理
                num %= scale;
				scale /= 10;
                continue;
            } else if (count <= 3) {
                for (; count > 0; count--) {
                    res.append(roman[i]);
                }
            } else if(count == 4) {
                res.append(roman[i]);
                res.append(roman[i + 1]);
            } else if (count == 5) {
                res.append(roman[i + 1]);
            } else if (count <= 8) {
                res.append(roman[i + 1]);
                for (int j = count - 5; j > 0; j--) {
                    res.append(roman[i]);
                }
            } else if(count ==9) {
                res.append(roman[i]);
                res.append(roman[i + 2]);
            }
            num %=scale;
            scale /= 10;
            
        }
        return res.toString();
    }
}

网上很多下面这种做法,感觉更简单了。

public class Solution {
	public String intToRoman(int num) {
		if(num <= 0) {
			return "";
		}
	    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"};
	    StringBuilder res = new StringBuilder();
	    int digit=0;
	    while (num > 0) {
	        int times = num / nums[digit];
	        num -= nums[digit] * times;
	        for ( ; times > 0; times--) {
	            res.append(symbols[digit]);
	        }
	        digit++;
	    }
	    return res.toString();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值