美文网首页
[LeetCode]12. Integer to Roman

[LeetCode]12. Integer to Roman

作者: Eazow | 来源:发表于2016-06-06 23:09 被阅读53次

    Given an integer, convert it to a roman numeral.

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

    方法

    将罗马数字和数字的对应关系从大到小列举出来,注意900、400、90、40、9、4这些数字对应的罗马字符

    c代码
    #include <assert.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* intToRoman(int num) {
        int vals[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
        char* strs[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        
        char* roman = (char *)malloc(sizeof(char) * 100);
        int i = 0;
        int length = sizeof(vals)/sizeof(int);
        for(i = 0; i < length; i++) {
            while(num >= vals[i]) {
                strcat(roman, strs[i]);
                num -= vals[i];
            }
        }
        return roman;
    }
    
    int main() {
        assert(strcmp(intToRoman(9), "IX") == 0);
    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode]12. Integer to Roman

          本文链接:https://www.haomeiwen.com/subject/addddttx.html