Integerto Roman Algorithm

The Integer to Roman Algorithm is a computational method used to convert a given integer into its corresponding Roman numeral representation. Roman numerals are an ancient numeral system, which uses a combination of letters from the Latin alphabet to denote numerical values. The basic symbols used in Roman numerals are I, V, X, L, C, D, and M, which stand for 1, 5, 10, 50, 100, 500, and 1000 respectively. The algorithm works by iteratively subtracting the largest possible Roman numeral values from the given integer and appending the corresponding Roman numeral symbols to the result until the integer is reduced to zero. To implement the Integer to Roman Algorithm, one can create a mapping of integer values to their corresponding Roman numeral symbols. This mapping can be stored as a list of tuples or a dictionary. The algorithm starts by iterating through the mapping and checking if the current integer value is greater than or equal to the Roman numeral value in the mapping. If it is, the algorithm subtracts the Roman numeral value from the integer and appends the corresponding Roman numeral symbol to the result. This process is repeated until the integer is reduced to zero, and the final Roman numeral representation is obtained. A key aspect of this algorithm is understanding the subtractive notation used in Roman numerals, where a smaller numeral placed before a larger numeral indicates subtraction, such as IV for 4 and XC for 90.
class Solution {
public:
    string intToRoman(int num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        char symbol[] = {'I', 'V', 'X', 'L','C', 'D', 'M'};
        string result;
        int base = 1000;
        int d = 6;
        while (num) {
            int digit = num / base;
            appendRoman(digit, result, symbol + d);
            d -= 2;
            num %= base;
            base /= 10;
        }
        return result;
    }
    
    void appendRoman(int n, string& s, char symbol[]) {
        assert(n <= 9);
        
        if (n == 0) return;
        if (n <= 3) {
            s.append(n, symbol[0]);
        }
        else if (n == 4) {
            s.append(1, symbol[0]);
            s.append(1, symbol[1]);
        }
        else if (n <= 8) {
            s.append(1, symbol[1]);
            s.append(n - 5, symbol[0]);
        }
        else if (n == 9) {
            s.append(1, symbol[0]);
            s.append(1, symbol[2]);
        }
    }
};

LANGUAGE:

DARK MODE: