c++ simple solution with simple explanation


  • 0
    X
    // the Roman seven symbols:
    // I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
    // the Roman rules:
    // the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
    // X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
    // C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern
    class Solution {
    public:
        string intToRoman(int num) {
            vector<int> i = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
            vector<string> r = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
            string ans;
            for(int j = 0; j < i.size(); ++j){
                while(num >= i[j]){
                    ans += r[j];
                    num -= i[j];
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.