12. Integer to Roman

Given an integer, convert it to a roman numeral.

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

char* intToRoman(int num) {
    char* ret = malloc(sizeof(char)*13); //Each digit at maximum be written as 3 Roman character
    char* p = ret;
    char roman[4][2]={
        'M', ' ',
        'C', 'D',
        'X', 'L',
        'I', 'V'
    };
    int result;
    int benchmark = 1000;
    
    for(int len = 0; len < 4; len++){
        result = num/benchmark;
        num = num%benchmark;
        if(9 == result){
            *p = roman[len][0];
            p++;
            *p = roman[len-1][0];
            p++;
        }
        else if( result >= 5){
            *p = roman[len][1];
            p++;
            for(int i = 0; i < result-5; i++){
                *p = roman[len][0];
                p++;
            }
        }
        else if(4 == result){
            *p = roman[len][0];
            p++;
            *p = roman[len][1];
            p++;
        }
        else{
            for(int i = 0; i < result; i++){
                *p = roman[len][0];
                p++;
            }
        }
        
        benchmark /= 10 ;
    }
    *p = '\0';
    return ret;
}

 

posted on 2016-04-08 22:55  joannae  阅读(160)  评论(0编辑  收藏  举报

导航