Leetcode ☞ 12. Integer to Roman ☆

12. Integer to Roman

My Submissions
Question
Total Accepted: 57002  Total Submissions: 151392  Difficulty: Medium

Given an integer, convert it to a roman numeral.

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









跟第13题Leetcode ☞ 13. Roman to Integer相反:http://blog.csdn.net/dr_unknown/article/details/50762420


我的AC(22ms,击败77%):

<span style="font-size:18px;">char* intToRoman(int num) {
    char* ans = (char*)calloc(20, sizeof(char));
    int index = 0;
    
    while(num >= 1000){
        ans[index++] = 'M';//M:1000
        num -= 1000;
    }
    if (num >= 900){
        ans[index++] = 'C';//C:100
        ans[index++] = 'M';//M:1000
        num -= 900;
    }
    if (num >= 500){
        ans[index++] = 'D';//D:500
        num -= 500;
    }
    if(num >= 400){
        ans[index++] = 'C';//C:100
        ans[index++] = 'D';//D:500
        num -= 400;
    }
    
    while(num >= 100){
        ans[index++] = 'C';//C:100
        num -= 100;
    }
    if (num >= 90){
        ans[index++] = 'X';//X:10
        ans[index++] = 'C';//C:100
        num -= 90;
    }
    if (num >= 50){
        ans[index++] = 'L';//L:50
        num -= 50;
    }
    if(num >= 40){
        ans[index++] = 'X';//X:10
        ans[index++] = 'L';//L:50
        num -= 40;
    }
    
    while(num >= 10){
        ans[index++] = 'X';//X:10
        num -= 10;
    }
    if (num >= 9){
        ans[index++] = 'I';//I:1
        ans[index++] = 'X';//X:10
        num -= 9;
    }
    if (num >= 5){
        ans[index++] = 'V';//V:5
        num -= 5;
    }
    if(num >= 4){
        ans[index++] = 'I';//I:1
        ans[index++] = 'V';//V:5
        num -= 4;
    }
    
    while(num){
        ans[index++] = 'I';
        num--;
    }
    
    ans[index] = '\0';
    return ans;
}</span>

分析:

1、4是5之前减一个1,8是5后面加三个1,9是10之前减一个1。知道这些就能知道罗马数字是如何组合的了。

2、此解法是很细的分情况。还有另外两种解法,时间一样:

C语言:https://leetcode.com/discuss/89381/three-simple-understanding-different-solutions-explained


你可能感兴趣的:(Leetcode ☞ 12. Integer to Roman ☆)