Roman to Integer - C Solution

1. Introduction

In this post, we will explore how to convert Roman numerals to integers in C programming. Roman numerals are a numeral system originating from ancient Rome, using combinations of letters from the Latin alphabet (I, V, X, L, C, D, M) to represent numbers. This problem is a good exercise in string manipulation and understanding how to implement classical algorithms in modern programming.

Problem

Given a string s representing a Roman numeral, the task is to convert it to an integer. The Roman numerals are based on specific rules where letters represent values, and are usually written from largest to smallest left to right, with some exceptions for subtraction.

2. Solution Steps

1. Map each Roman numeral symbol to its corresponding integer value.

2. Initialize an integer result to store the final number.

3. Iterate through the Roman numeral from left to right.

4. For each symbol, add its value to result. If a symbol is less than its successor, subtract it instead.

5. Return the final result.

3. Code Program

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

// Function to convert Roman numeral to integer
int romanToInt(char * s) {
    int result = 0;
    int prevValue = 0;

    for (int i = strlen(s) - 1; i >= 0; i--) {
        int value = 0;

        switch (s[i]) {
            case 'I': value = 1; break;
            case 'V': value = 5; break;
            case 'X': value = 10; break;
            case 'L': value = 50; break;
            case 'C': value = 100; break;
            case 'D': value = 500; break;
            case 'M': value = 1000; break;
        }

        if (value < prevValue) {
            result -= value;
        } else {
            result += value;
        }
        prevValue = value;
    }

    return result;
}

// Main function to test the romanToInt function
int main() {
    char s1[] = "III";
    printf("Integer of Roman Numeral 'III': %d\n", romanToInt(s1));

    char s2[] = "LVIII";
    printf("Integer of Roman Numeral 'LVIII': %d\n", romanToInt(s2));

    char s3[] = "MCMXCIV";
    printf("Integer of Roman Numeral 'MCMXCIV': %d\n", romanToInt(s3));

    return 0;
}

Output:

Integer of Roman Numeral 'III': 3
Integer of Roman Numeral 'LVIII': 58
Integer of Roman Numeral 'MCMXCIV': 1994

Explanation:

1. int result = 0; - Initialize the result variable.

2. for (int i = strlen(s) - 1; i >= 0; i--) - Iterate through the Roman numeral string from right to left.

3. switch (s[i]) - Determine the integer value of each Roman numeral symbol.

4. if (value < prevValue) { result -= value; } - Apply subtraction rule for specific Roman numeral cases.

5. else { result += value; } - Otherwise, add the value to the result.

6. prevValue = value; - Keep track of the previous value for the subtraction rule.

7. The main function tests the romanToInt function with three examples and prints the integer equivalents of the Roman numerals.


Comments