LeetCode----12. Integer to Roman

来源:互联网 发布:创新创业网络课程答案 编辑:程序博客网 时间:2024/05/29 09:36

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

罗马数字:

I: 1;    V:5;    X:10  L:50    C:100   D:500   M:1000

4:IV     9:IX 

40: XL   90:XC

400:CD  900:CM

//也可以用数组进行存储

public class Solution {    public String intToRoman(int num) {        String s="";        if(num>=1&&num<=3999){            int i=num/1000;while(i!=0){s+="M";i--;}num=num%1000;            int j=num/100;if(j>=1&&j<=3){while(j!=0){s+="C";j--;}}else if(j==4){s+="CD";}else if(j==5){s+="D";}else if(j>=6&&j<=8){s+="D";                j=j-5;while(j!=0){s+="C";j--;} }if(j==9){s+="CM";}num=num%100;                        int K=num/10;if(K>=1&&K<=3){while(K!=0){s+="X";K--;}}else if(K==4){s+="XL";}else if(K==5){s+="L";}else if(K>=6&&K<=8){s+="L";                K=K-5;while(K!=0){s+="X";K--;}} if(K==9){s+="XC";}num=num%10;                         int q=num;if(q>=1&&q<=3){while(q!=0){s+="I";q--;}}else if(q==4){s+="IV";}else if(q==5){s+="V";}else if(q>=6&&q<=8){s+="V";                q=q-5;while(q!=0){s+="I";q--;} }if(q==9){s+="IX";}            return s;        }        return null;    }           }


0 0
原创粉丝点击