美文网首页
Integer to Roman: An Almost Hard

Integer to Roman: An Almost Hard

作者: 刘煌旭 | 来源:发表于2020-11-22 15:32 被阅读0次

Problem Specs:


roman.png

Solution(Implemented in C):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "out.c"
/**
 * Abstract: Solution immediately present itself from the problem specs; 
 * the code here is trivial & does not to be explained. 
 * Warning:Compliers handle c strings differently: it might be okay to drop the 
 * trailing '\0' or it might NOT be okey; the letter is the case with LC.
 * NOTE: Test client main() prints every test case.
 */
char * intToRoman(int num){
    char *ind[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    char *ten[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    char *hun[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    char *tho[] = {"", "M", "MM", "MMM"};
    int n = num;
    char *roman = (char*)malloc((3 + 4 + 4 + 4 + 1) * sizeof(*roman));
    char **rd[] = {ind, ten, hun, tho};
    int sig = -1;
    int digits[4] = {0};
    while (n > 0) {
        digits[++sig] = n % 10;
        n /= 10;
    }
    *roman = '\0';
    while (sig >= 0) {
        strcat(roman, rd[sig][digits[sig]]);
        sig--;
    }
    roman[strlen(roman)] = '\0';
    return roman;
}

int main(void) {
    for (int i = 1; i < 4000; i++) { printf("i = %i, roman = %s\n", i, intToRoman(i)); }
    return 0;
}

相关文章

网友评论

      本文标题:Integer to Roman: An Almost Hard

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