[LeetCode12]Integer to Roman

178 篇文章 6 订阅
106 篇文章 0 订阅

Given an integer, convert it to a roman numeral.

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

Analysis:

The key point is how to handle every digit.

1<=digit<=3

digit=4

digit =5

5<digit<=8

digit = 9

Java

public String intToRoman(int num) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        String[] symbol ={"I","V","X","L","C","D","M"};
        String roman="";
        int scale = 1000;
        for(int i=6;i>=0;i-=2){
        	int digit = num/scale;
        	if(digit!=0){
        		if(digit<=3)
        			while((digit--)>0)
        				roman+=symbol[i];
        		else if(digit == 4){
        			roman+=symbol[i];
        			roman+=symbol[i+1];
        		}
        		else if(digit ==5)
        			roman+=symbol[i+1];
        		else if(digit <=8){
        			roman+=symbol[i+1];
        			while(((digit--)-5)>0)
        				roman+=symbol[i];
        		}
        		else if(digit ==9){
        			roman+=symbol[i];
        			roman+=symbol[i+2];
        		}
        			
        	}
        	num = num%scale;
        	scale/=10;
        }
        return roman;
    }
c++

string intToRoman(int num) {
    char symbol[7] = {'I','V','X','L','C','D','M'};
    string roman;
    int scale = 1000;
    for(int i=6;i>=0;i-=2){
        int digit = num/scale;
        if(digit!=0){
            if(digit<=3){
                roman.append(digit,symbol[i]);
            }else if(digit == 4){
                roman.append(1,symbol[i]);
                roman.append(1,symbol[i+1]);
            }else if(digit == 5){
                roman.append(1,symbol[i+1]);
            }else if(digit<=8){
                roman.append(1,symbol[i+1]);
                roman.append(digit-5,symbol[i]);
            }else if(digit == 9){
                roman.append(1,symbol[i]);
                roman.append(1,symbol[i+2]);
            }
        }
        num = num%scale;
        scale /=10;
    }
    return roman;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值