C Systems Programming & LeetCode 12

Number to Roman in C Language

A high-performance Greedy Algorithm implementation of Integer to Roman in C. Step through memory buffers in the live execution playground, copy production C source code, and explore reverse pointer parsing.

Interactive C Trace Visualizer

Greedy Loop Step Simulator

Try benchmarks:
Terminal stdout & buffer memory Output: MCMXCIV
Production Implementation

1. Complete C Code: intToRoman()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* intToRoman(int num) {
    static const int values[] = {
        1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
    };
    static const char* symbols[] = {
        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
    };

    char* result = (char*)malloc(16 * sizeof(char));
    if (!result) return NULL;
    result[0] = '';

    for (int i = 0; i < 13 && num > 0; i++) {
        while (num >= values[i]) {
            strcat(result, symbols[i]);
            num -= values[i];
        }
    }

    return result;
}

int main(void) {
    int testNum = 1994;
    char* roman = intToRoman(testNum);
    printf("%d in Roman is: %s
", testNum, roman);
    free(roman);
    return 0;
}

2. Reverse C Function: romanToInt()

For bidirectional support, here is the companion C lookahead parser:

int charToValue(char c) {
    switch(c) {
        case 'I': return 1;
        case 'V': return 5;
        case 'X': return 10;
        case 'L': return 50;
        case 'C': return 100;
        case 'D': return 500;
        case 'M': return 1000;
        default: return 0;
    }
}

int romanToInt(const char* s) {
    int total = 0;
    int len = strlen(s);

    for (int i = 0; i < len; i++) {
        int current = charToValue(s[i]);
        int next = (i + 1 < len) ? charToValue(s[i + 1]) : 0;

        if (current < next) {
            total -= current;
        } else {
            total += current;
        }
    }

    return total;
}

Number to Roman in C FAQs

What is the algorithm for integer to Roman in C?

The standard approach is the Greedy Algorithm. We define two parallel static arrays: one for integer values {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1} and one for corresponding Roman string symbols {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}. Iterating through the arrays, we subtract the largest possible value and append its symbol until the number reaches zero.

What is the time and space complexity of integer to Roman in C?

Both time and space complexity are O(1) constant time. Because the input range is capped between 1 and 3,999, the loops execute at most 15 times and the output string never exceeds 15 characters (e.g., MMMDCCCLXXXVIII).

How much memory should be allocated for a Roman numeral string in C?

A dynamically allocated buffer of 16 bytes (15 characters plus 1 null-terminator byte \0) is sufficient to store any standard Roman numeral up to 3,999.