码迷,mamicode.com
首页 > 其他好文 > 详细

12. Integer to Roman

时间:2016-04-09 00:07:53      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 

12. Integer to Roman

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5370293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!