LeetCode刷题笔记-12.整数转罗马数字

LeetCode刷题笔记-12.整数转罗马数字

  • C代码
    • 注意点
    • 结果
  • 题目

C代码


int vals[] = {
    1000,
    900,
    500,
    400,
    100,
    90,
    50,
    40,
    10,
    9,
    5,
    4,
    1
};

char *rs[] = {
    [1000] = "M",
    [900] = "CM",
    [500] = "D",
    [400] = "CD",
    [100] = "C",
    [90] = "XC",
    [50] = "L",
    [40] = "XL",
    [10] = "X",
    [9] = "IX",
    [5] = "V",
    [4] = "IV",
    [1] = "I"
};

char * intToRoman(int num){
    int i;
    char *ret = NULL;
    int size = 0;
    int cap = 1 << 10;
    int cs = 0;
    
    ret = calloc(cap, sizeof(char));
    for (i = 0; i < 13; i++) {
        while(num >= vals[i]) {
            cs = strlen(rs[vals[i]]);
            num -= vals[i];
            if(size >= (cap - 3)) {
                cap = cap << 1;
                ret = realloc(ret, cap * sizeof(char));
            }
            strncpy(ret+size, rs[vals[i]], cs);
            size += cs;
        }
    }
    ret[size] = '\0';
    return ret;
}

注意点

  1. 转换类型的数组的长度为13个;
  2. 组装ret返回字符串的偏移需要控制,先判断空间是否最小预留3个,再拷贝字符串,最后统计最新的字符串长度size;
  3. 注意映射表的建立,曾缺失[9]="IX",的条目导致报错;

结果

LeetCode刷题笔记-12.整数转罗马数字_第1张图片

题目

LeetCode刷题笔记-12.整数转罗马数字_第2张图片
LeetCode刷题笔记-12.整数转罗马数字_第3张图片

你可能感兴趣的:(算法刷题,leetcode,c语言,算法)