leetcode integer to roman number conversion

本文介绍了一种使用Java实现的方法,将给定的整数转换为其对应的罗马数字表示。遵循了从大到小的原则进行计算,并详细解释了内部逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer, convert it to a roman numeral.

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

This is also a google interview problem!

I = 1   can be subtracted from 5, 10
V = 5
X = 10 can be subtracted from 50, 100
L = 50
C = 100 can be subtracted from 500, 1000
D = 500 
M = 1000

3 = III
30 = XXX

4 = IV
9 = IX

IIX wrong
8 = VIII

1999 = IMM wrong
MCMXCIX = 1999

999 = CM XC IX 

you can check wiki to get known of the rules.

I do it by dividing and conquer. always get the biggest smaller number to subtract then do the same to the remainings.

public class Solution {
    public static String intToRoman(int num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        HashMap h=new HashMap();
        h.put(1,'I');
        h.put(5,'V');
        h.put(10,'X');
        h.put(50,'L');
        h.put(100,'C');
        h.put(500,'D');
        h.put(1000,'M');
        int a[]={1,5,10,50,100,500,1000};
        StringBuilder s=new StringBuilder();
        
        return new String(get(num,s,h,a));
        
    }
    public static int search(int a[], int x){
        int i=a.length-1;
        while(i>=0&&a[i]>x) i--;
        return i;
    }
    
    public static StringBuilder get(int x,StringBuilder s,HashMap h, int a[]){
        if(h.containsKey(x)){s.append(h.get(x)); return s;}
        if(x==0) return s;

        int c=search(a,x);
        
        if(x<4*a[c]){
            if((c&1)==1&&c<6&&a[c+1]-a[c-1]<=x){//this rule is just for 9->IX not VIV
                x=x-a[c+1]+a[c-1];//actually I don't understand this rule well
                s.append(h.get(a[c-1]));
                s.append(h.get(a[c+1]));
            }
            else if(x<2*a[c]) {
                x-=a[c];
                s.append(h.get(a[c]));
                }
            else if(x<3*a[c]){
                x-=2*a[c];
                s.append(h.get(a[c]));
                s.append(h.get(a[c]));}
            else if(x>=3*a[c]){
                x-=3*a[c];
                s.append(h.get(a[c]));
                s.append(h.get(a[c]));
                s.append(h.get(a[c]));
            }
            return get(x,s,h,a);
}

        else{
            x=a[c+1]-x;
            if(c>0&&x<=a[c-1]&&((c&1)==1)){
                x=a[c-1]-x;
                s.append(h.get(a[c-1]));
                s.append(h.get(a[c+1]));}
            else if(x<=a[c]&&((c&1)==0)){
                x=a[c]-x;
                s.append(h.get(a[c]));
                s.append(h.get(a[c+1]));}
            else {s.append(h.get(a[c+1]));}
            return get(x,s,h,a);}
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值